1.导入spring-webmvc坐标
首先在项目的pom.xml文件中添加SpringMVC需要的spring-webmvc坐标
初次之外还要导入常用到的servleti和jsp的坐标
2.配置SpringMVC的前端控制器:DispatcherServlet
和普通的servlet一样,需要在web.xml中注册servlet并添加请求映射:
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.编写Controller类和页面视图
把要跳转的页面写在webapp文件夹下,例如success.jsp
然后编写一个Controller层的类以及它的方法:
public class UserController {
public String success(){
System.out.println("UserController object.success() method is called......");
return "success.jsp";
}
}
4.使用注解配置Controller类中的方法与请求映射
- 首先,在我的UserController类上加上@Controller注解,把它放到Spring容器中去
- 然后,在success方法上添加@RequestMapping("/success")注解
@Controller
public class UserController {
@RequestMapping("/success")
public String success(){
System.out.println("UserController object.success() method is called......");
return "success.jsp";
}
}
5.配置SpringMVC和核心配置文件spring-mvc.xml
在resources文件夹下创建一个配置文件:spring-mvc.xml
添加context的命名空间,然后添加controller层的组件扫描
最后去前端控制器DispatcherServlet中配置init-param,告诉它SpringMVC的配置文件放在哪
spring-mvc.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"
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">
<!--配置SpringMVC的组件扫描-->
<context:component-scan base-package="com.lxl.controller"/>
</beans>
在刚才注册DispatcherServlet的地方加上SpringMVC的配置文件位置:
<!--配置SpringMVC的前端控制器:DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
这节博客对应我的Spring-05-mvc项目,是在Spring-04-web项目上进行添加得到的
我的代码的地址:https://github.com/RamboKingder/Spring_Learning