1.下载依赖,建立web工程,导入jar包
所需要的依赖包有下面这些
关于springMVC的jar包主要是最后两个。
建立web工程导入jar包这些步骤省略
2.在web.xml文件中配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--配置前端控制器-->
<servlet>
<!--配置名字-->
<servlet-name>springMvc</servlet-name>
<!--对应的类 DispatcherServlet-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--初始化参数需要传入contextConfigLocation即springMvc的配置文件所在-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-servlet.xml</param-value>
</init-param>
<!--配置加载的优先级-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置servlet映射-->
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<!--拦截处理当前工程下所有请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.书写后端控制器类和方法
3.1 给类加上@Controller注解标明这是一个控制器类
3.2 (非必需)可以给类加上访问路径@RequestMapping ("")
3.3 书写控制器方法,加上访问路径@RequestMapping ("")
示例如下
/**
* 配置后端控制器
*/
@Controller
@RequestMapping("/user")
public class UserController {
//直接返回视图
@RequestMapping("/show")
public String show(String userName){
System.out.println(userName);
return "show";
}
}
4.配置application-servlet.xml文件
该文件为SpringMvc的配置文件,文件名由你自己定义,注意和web.xml中contextConfigLocation所配置的文件名保持一致,该文件需要放在源文件夹下。
4.1 配置视图解析器(解析我们从后端控制器返回的视图格式)
4.2 开启 mvc:annotation-driven 支持后端控制器,并且和后期的json、map解析有关
4.3 开启我们的注解扫描
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 开启注解扫描-->
<context:component-scan base-package="com.openlab.controller"></context:component-scan>
</beans>
5.进行测试
测试流程:
运行tomcat服务器,在浏览器输入localhost:8080/mvc/user/show(/mvc 是我的web工厂名 ,/user是后端控制器类配置的访问路径,/show 是控制器中的方法配置的访问路径)浏览器发送请求,前端控制器接收请求转发给后端控制器。后端控制器执行业务流程,返回了"show",经过视图解析器,解析为了web根目录下的/show.jsp响应给浏览器进行显示。
上面三个结果图对应着方法中的三步流程