一、首先导包
导入 maven 依赖,pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
二、新建一个实现 controller 接口的类
package com.lwj.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class FirstController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
ModelAndView mv = new ModelAndView();
// 其实底层执行的是request.setAttribute()方法
mv.addObject("name", "张三");
// 添加视图名称:路径+文件名
mv.setViewName("/WEB-INF/jsp/welcome.jsp");
//返回后将自动跳转到该页面
return mv;
}
}
三、新建 springMVC.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
//注册处理器
<bean class="com.lwj.controller.FirstController" id="/firstController.action"></bean>
</beans>
四、在 web.xml 中添加代码
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<!-- 需要加载的 springMVC 文件 -->
<servlet-name>springMVC</servlet-name>
<!-- 对应的java类 -->
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如springMVC-servlet.xml --><init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!-- 启动就加载 springMVC 配置文件 -->
<load-on-startup>1</load-on-startup> </servlet> <!-- Servlet映射 -->
<servlet-mapping> <!-- 请求对应的Servlet的名称 --> <servlet-name>springMVC</servlet-name> <!-- 监听当前域的所有请求 --> <url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
最后在浏览器中请求 /firstController 就可以跳转到 /WEB-INF/jsp/welcome.jsp 页面