参考:1.佟刚老师视频
2.史上最全最强SpringMVC详细示例实战教程
SpringMVC学习笔记----
一、SpringMVC基础入门,创建一个HelloWorld程序
1.首先,导入SpringMVC需要的jar包。
2.添加Web.xml配置文件中关于SpringMVC的配置
(1)通过 contextConfigLocation 来配置 SpringMVC 的配置文件


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 配置 DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 -->
<!--
实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--配置 此servlet在web应用加载时被创建 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!--配置 使dispatcherServlet可以应答所有请求 -->
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
View Code
(2)不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
如: /WEB-INF/dispatcherServlet-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 配置 DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
View Code
3.在src下添加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: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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.atguigu.springmvc"/>
<!-- don't handle the static resource -->
<mvc:default-servlet-handler />
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven />
<!-- configure the InternalResourceViewResolver
配置视图解析器:如何把handler方法返回值解析为实际的物理视图
-->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
View Code
4.在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个hello.jsp,在body中添加“Hello World”。
5.建立包及Controller,如下所示

6.编写Controller代码


@Controller
@RequestMapping("/helloWorld")
public class HelloWorld {
/**
1.使用 @RequestMapping 注解来映射请求的URL
2.返回值会通过视图解析器解析为实际的物理视图,对 InternalResourceViewResolver 视图解析器,会做如下的解析:
通过 prefix + returnVal + 后缀 这样的方式得到实际的物理视图,然后会做转发操作
如: /WEB-INF/views/success.jsp
*/
@RequestMapping("/hello")
public String hello(){
System.out.println("hello world");
return "success";
}
}
View Code
7.启动服务器,键入 http://localhost:8080/项目名/helloWorld/hello
二、配置解析
1.Dispatcherservlet
DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。
2.InternalResourceViewResolver
视图名称解析器
3.以上出现的注解
@Controller 负责注册一个bean 到spring 上下文中
@RequestMapping 注解为控制器指定可以处理哪些 URL 请求
三、SpringMVC常用注解之 请求参数
1.@Controller
负责注册一个bean 到spring 上下文中
2.@RequestMapping
(1) DispatcherServlet 截获请求后,就通过控制器上 @RequestMapping 提供的映射信息确定请求所对应的处理方法。
(2) 可修饰在两个地方:
类定义处:提供初步的请求映射信息 ,相对于 WEB 应用的根目录
方法处 :提供进一步的细分映射信息,相对于类定义处的 URL 。若类定义处未标注 @RequestMapping,则方法处标记的 URL 相对于WEB 应用的根目录
(3)@RequestMapping 除了可以使用请求 URL 映射请求外,还可以使用 请求方法、请求参数 及 请求头映射请求
@RequestMapping 的 value、method、params 及 heads分别表示请求 URL、请求方法、请求参数 及 请求头 的映射条件,他们之间是 与 的关系,联合使用多个条件可让请求映射更加精确化。
2.1 @RequestMapping 请求方法-method


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
常用:使用 method 属性指定请求方式
使用 value 属性指定请求的url
*/
@RequestMapping(value="/testMethod" ,method=RequestMethod.POST)
public String testMethod(){
System.out.println(" testMethod ");
return "success";
}
}
View Code
2.2 @RequestMapping 请求参数-params
params 和 headers支持简单的表达式:
(1) param1: 表示请求必须包含名为 param1 的请求参数
(2) !param1: 表示请求不能包含名为 param1 的请求参数
(3) param1 != value1: 表示请求包含名为 param1 的请求参数,但其值不能为 value1
(4) {"param1=value1", "param2"}: 请求必须包含名为 param1 和param2的两个请求参数,且 param1 参数的值必须为 value1


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
前端请求url: <a href="springmvc/testParamsAndHeaders?username=ray&age=10">Test Method</a>
*/
@RequestMapping(value="/testMethod" ,params={"username","age!=10"})
public String testParamsAndHeaders(){
System.out.println(" testMethod ");
return "success";
}
}
View Cod
2.3 @RequestMapping Ant路径
Ant 风格资源地址支持 3 种匹配符:
– ?:匹配文件名中的一个字符
– *:匹配文件名中的任意字符
– **:** 匹配多层路径
@RequestMapping 还支持 Ant 风格的 URL:
– /user/*/createUser: 匹配
/user/aaa/createUser、/user/bbb/createUser 等 URL
– /user/**/createUser: 匹配
/user/createUser、/user/aaa/bbb/createUser 等 URL
– /user/createUser??: 匹配
/user/createUseraa、/user/createUserbb 等 URL


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
@RequestMapping("/testAntPath/*/abc")
public String testAntPath(){
System.out.println(" testAntPath ");
return "success";
}
}
View Code
3.@RequestMapping_PathVariable 注解
通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:
URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
前端URL: "springmvc/testPathVariable/1"
@PathVariable 可以映射 URL 中的占位符到目标方法的参数中
*/
@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id){
System.out.println(" testPathVariable " +id);
return "success";
}
}
View Code
4.HiddenHttpMethodFilter 过滤器
4.1 相关概念
(1)REST:即 Representational State Transfer。(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用
(2) 资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的 URI 。要获取这个资源,访问它的URI就可以,因此 URI 即为每一个资源的独一无二的识别符。
(3)表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层(Representation)。比如,文本可以用 txt 格式表现,也可以用 HTML 格式、XML 格、JSON 格式表现,甚至可以采用二进制格式。
(4) 状态转化(State Transfer):每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生“状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是 “表现层状态转化”。
具体说,就是 HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。
(5)HiddenHttpMethodFilter:浏览器 form 表单只支持 GET与 POST 请求,而DELETE、PUT 等 method 并不支持,Spring3.0 添加了一个过滤器,可以将这些请求转 换为标准的 http 方法,使得支持 GET、POST、PUT 与DELETE 请求。
4.2 实现rest风格的增删改查 代码实例
(1)在web.xml文件中配置HiddenHttpMethodFilter:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 1. 配置 DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--
2. 配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 请求转为 DELETE 或 POST 请求
-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
View Code
(2)前端页面关键代码
通过隐藏一个name="_method" 的input按钮,来实现表单中POST请求向DELETE 与PUT请求的转化。


<a href="springmvc/testRest/1">Test Rest Get</a>
<br></br>
<from action-"springmvc/testRest" method="post">
<input type="submit" value="TestRest POST"/>
</from>
<br></br>
<from action-"springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="DELETE" />
<input type="submit" value="TestRest DELETE"/>
</from>
<br></br>
<from action-"springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="PUT" />
<input type="submit" value="TestRest PUT"/>
</from>
View Code
(3)后端Java代码


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
Rest风格的URL 以前的旧风格
以CRUD为例:
新增:/order PSOT
修改:/order/1 PUT update?id=1
获取:/order/1 GET get?id=1
删除:/order/1 DELETE delete?id=1
如何发送PUT请求和DELETE请求呢?
1.需要配置HiddenHttpMethodFilter
2.需要发送POST请求
3.需要再发送POST请求时携带一个name="_method"的隐藏域,值为DELETE或PUT
在Spring MVC的目标方法中如何得到id呢?
使用@PathVariable注解
*/
//1. get 获取
@RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
public String testRest(@PathVariable("id") Integer id){
System.out.println(" testRest GET " +id);
return "success";
}
//2. POST 新建
@RequestMapping(value="/testRest",method=RequestMethod.POST)
public String testRest(){
System.out.println(" testRest POST " ;
return "success";
}
//3. DELETE 删除
@RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
public String testRestDelete(@PathVariable("id") Integer id){
System.out.println(" testRest DELETE " +id);
return "success";
}
//4. PUT 更新
@RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
public String testRestPut(@PathVariable("id") Integer id){
System.out.println(" testRest PUT " +id);
return "success";
}
}
View Code
5. @RequestParam 绑定请求参数
使用 @RequestParam 绑定请求参数值 :在处理方法入参处使用 @RequestParam 可以把请求参数传递给请求方法。


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
一.前端代码: <a href="springmvc/testRequestParam?username=ray&age=11">Test RequestParam</a>
<br></br>
<a href="springmvc/testRequestParam2?username=ray">Test RequestParam2</a>
<br></br>
二.知识点:
@RequestParam 来映射请求参数。
value 值即请求参数的参数名
required 该参数是否必须。默认为true
defaultValue 请求参数的默认值
*/
@RequestMapping(value="/testRequestParam")
public String testRequestParam(@RequestParam(value="username") String un,
@RequestParam(value="age") int age ){
System.out.println(" testRequestParam ,username="+un+",age="+age );
return "success";
}
//在地址栏可不传age参数过来,required=false表示此参数不是必须的
@RequestMapping(value="/testRequestParam2")
public String testRequestParam2(@RequestParam(value="username") String un,
@RequestParam(value="age",required=false,defaultValue="0") int age ){
System.out.println(" testRequestParam ,username="+un+",age="+age );
return "success";
}
}
View Code
6.@RequestHeader 绑定请求报头的属性值
请求头的属性值可以在浏览器的开发者工具中的网络里面查看


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
一.前端代码: <a href="springmvc/testRequestHeader">Test RequestHeader</a>
<br></br>
二.知识点
映射请求头信息
用法同@RequestParam
了解即可
*/
@RequestMapping(value="/testRequestHeader")
public String testRequestHeader(@RequestHeader(value="Accept-Language" String al) ){
System.out.println(" testRequestHeader ,Accept-Language="+al );
return "success";
}
}
View Code
7. @CookieValue 绑定请求中的 Cookie 值


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
一.前端代码: <a href="springmvc/testCookieValue">Test testCookieValue</a>
<br></br>
二.知识点
@CookieValue:映射一个Cookie值,属性同@RequestParam
了解即可
*/
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String sessionId){
System.out.println(" testCookieValue: sessionId" +sessionId);
return "success";
}
}
View Code
8.使用 POJO 对象绑定请求参数值
Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配,自动为该对象填充属性值。支持级联属性。如:dept.deptId、dept.address.tel 等


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
一.前端代码:
<from action-"springmvc/testPojo" method="post">
username:<input type="text" name="username"/>
<br>
password:<input type="password" name="password"/>
<br>
email:<input type="text" name="email"/>
<br>
age:<input type="text" name="age"/>
<br>
city:<input type="text" name="address.city"/>
<br>
province:<input type="text" name="address.province"/>
<br>
<input type="submit" value="Submit"/>
</from>
*/
@RequestMapping("/testPojo")
public String testPojo(User user){
System.out.println(" testPojo:"+user);
return "success";
}
}
View Code
9.使用Servlet原生API作为参数


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
一.前端代码:
<a href="springmvc/testServletAPI">Test ServletAPI</a>
二.知识点
可以使用servlet原生的API作为目标方法的参数,具体支持以下类型:
HttpServletRequest
HttpServletResponse
HttpSession
java.security.Principal
Locale
InputStream
OutputStream
Reader
Writer
*/
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request,
HttpServletResponse response,Writer out){
System.out.println(" testServletAPI:"+ request+","+response);
out.write("hello springmvc");
//return "success";
}
}
View Code
四、SpringMVC常用注解之 处理模型数据
Spring MVC 提供了以下几种途径输出模型数据:
– ModelAndView: 处理方法返回值类型为 ModelAndView时, 方法体即可通过该对象添加模型数据
– Map 及 Model: 入参为 org.springframework.ui.Model、org.springframework.ui.ModelMap 或 java.uti.Map 时,处理方法返回时,Map中的数据会自动添加到模型中。
– @SessionAttributes: 将模型中的某个属性暂存到HttpSession 中,以便多个请求之间可以共享这个属性
– @ModelAttribute: 方法入参标注该注解后, 入参的对象就会放到数据模型中
1.ModelAndView
• 控制器处理方法的返回值如果为 ModelAndView, 则其既包含视图信息,也包含模型数据信息。
• 添加模型数据:
– MoelAndView addObject(String attributeName, ObjectattributeValue)
– ModelAndView addAllObject(Map<String, ?> modelMap)
• 设置视图:
– void setView(View view)
– void setViewName(String viewName)


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
一.前端代码:
index.jsp: <a href="springmvc/testModelAndView">Test ModelAndView</a>
success.jsp: time:${requestScope.time}
二.知识点
目标方法的返回值可以是 ModelAndView 类型。
其中可以包含视图和模型信息。
SpringMVC会把ModelAndView的model中数据放入到request域对象中,以便在返回页面接收数据
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String viewName="success";
ModelAndView modelAndView=new ModelAndView(viewName);
//添加模型数据到ModelAndView 中.
modelAndView.addObject("time",new Date());
return modelAndView;
}
}
View Code
2.Map 或 Model 或 ModelMap


@Controller
@RequestMapping("/springmvc")
public class SpringMVCTest {
/**
一.前端代码:
index.jsp: <a href="springmvc/testMap">Test Map</a>
success.jsp: names:${requestScope.names}
二.知识点
目标方法可以添加Map类型(实际上也可以是Model类型或ModelMap类型)的参数
*/
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
System.out.println(map.getClass().getName());
map.put("names",Arrays.asList("Tom","Jerry","Mike"));
return "success";
}
}
View Code
3.@SessionAttributes
若希望在多个请求之间共用某个模型属性数据,则可以在控制器类上标注一个 @SessionAttributes, Spring MVC将在模型中对应的属性暂存到 HttpSession 中。


@SessionAttributes(value={"user"},types={String.class})
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
/**
一.前端代码:
index.jsp: <a href="springmvc/testSessionAttributes">Test SessionAttributes</a>
success.jsp: request user :${requestScope.user}
<br><br>
session user :${sessionScope.user}
<br><br>
request school :${requestScope.school}
<br><br>
session school :${sessionScope.school}
<br><br>
二.知识点
1.用法
@SessionAttributes除了可以通过属性名指定需要放到会话中的属性外 (实际上使用的是value属性值)
还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中 (实际上使用的是types属性值)
2.注意:该注解只能放在类的上面,而不能修饰方法
*/
@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Map<String,Object> map){
User user=new User("Tom","123456","tom@atguigu.com",15);
map.put("user",user);
map.put("schoool","atguigu");
return "success";
}
}
View Code
4. @ModelAttribute
一.知识点
1.有@ModelAttribute 标记对的方法,会在每个方法执行之前被SpringMVC调用
2.运行流程:
(1)执行@ModelAttribute 注解修饰的方法;从数据库中取出对象,把对象放入到Map中,键为user
(2)SpringMVC从Map中取出对象,并把表单的请求参数赋给该User对象的对应属性
(3)Spring把上述对象传入目标方法的参数。(以便被前台页面接收)
3.注意:在@ModelAttribute 修饰的方法中,放入到Map时的键需要和目标方法入参类型的第一个字母小写的字符串一致。
二.源码分析的流程:
1.调用@ModelAttribute注解修饰的方法,实际上把@ModelAttribute方法中Map中的数据放在了implicitModel中。
2.解析请求处理器的目标参数,实际上该目标参数来自于WebDataBinder对象的target属性
1).创建WebDataBinder对象:
①.确定objectName属性:若传入的attrName属性为"",则objectName为类名第一个字母小写。
*注意:attrName.若目标方法的POJO属性使用了@ModelAtrribute来修饰,则attrName值即为@ModelAttibute的value属性值。如:
public String testModelAttribute(@ModelAttribute("user") User user)
②确定target属性;
>在implicitModel中查找attrName对应的属性值。若存在,ok.
>*若不存在:则验证当前Handler是否使用了@SessionAttributes进行修饰,若使用了,则尝试从Session中获取attrName所对应的属性值。若session中没有对应属性值,则抛出异常。
>若Handler没有使用@SessionAtrributes进行修饰,或@SessionAttributes中没有使用value值指定的key和attrName相匹配,则通过反射创建POJO对象。
2).SpringMVC把请求表单的请求参数赋给了WebDataBinder的target对应的属性
3).*SpringMVC会把WebDataBinder的attrName和target给到implicitModel,进而传到request域对象中
4).把WebDataBinder的target作为参数传递给目标方法的入参。
三.SpringMVC确定目标方法POJO类型入参的过程
1.确定一个key:
1)若目标方法的POJO类型的参数没有使用@ModelAttribute作为修饰,则key为POJO类名第一个字母小写。
2)若使用了@ModelAttribute来修饰,则key为@ModelAttribute注解的value属性值。
2.在ImplicitModel中查找key对应的对象,若存在,则作为入参传入
1)若在@ModelAttribute标记的方法中在Map中保存过,且key和1确定的key一直,则会获取到。
3.若implicitModel中不存在对应的对象,则检查当前的Handler是否使用@SessionAttributes注解修饰,若使用了该注解,且@SessionAttributes注解的value属性值中包含了key,则会从HttpSession中来获取key所对应的value值,若存在则直接传入到目标方法的入参中,若不存在则抛出异常。
4.若Handler没有标识@SessionAttributes注解或@SessionAttributes注解的value值不包含key,则会通过反射来创建POJO类型的参数,传入为目标方法的参数。
5.SpringMVC会把key和value保存到implicitModel中,进而会保存到request中。


//@SessionAttributes(value={"user"},types={String.class})
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
/**
模拟修改操作
1.原始数据为:1,Tom,123456,tom@atguigu.com,12. 年龄改为13
2.密码不能被修改。
3.表单回显,模拟操作直接在表单填写对应的属性值
一.前端代码:
index.jsp:
<form action="springmvc/testModelAttribute" method="Post">
<input type="hidden" name="id" value="1" />
username: <input type="text" name="username" value="Tom"/>
<br>
email:<input type="text" name="email" value="tom@atguigu.com" />
<br>
age:<input type="text" name="age" value="13" />
<br>
<input type="submit" value="Submit" />
</form>
二.知识点
1.有@ModelAttribute 标记对的方法,会在每个方法执行之前被SpringMVC调用
@ModelAttribute注解也可以来修饰目标方法POJO类型的入参,其value属性值有如下的作用:
1)SpringMVC会使用value属性值在implicitModel中查找对应的对象,若存在则会直接传入到目标方法的入参中。
2)SpringMVC会以value为key,POJO类型的对象为value,存入到request中。
2.运行流程:
(1)执行@ModelAttribute 注解修饰的方法;从数据库中取出对象,把对象放入到Map中,键为user
(2)SpringMVC从Map中取出对象,并把表单的请求参数赋给该User对象的对应属性
(3)Spring把上述对象传入目标方法的参数。(以便被前台页面接收)
3.注意:在@ModelAttribute 修饰的方法中,放入到Map时的键需要和目标方法入参类型的第一个字母小写的字符串一致。
二.源码分析的流程:
1.调用@ModelAttribute注解修饰的方法,实际上把@ModelAttribute方法中Map中的数据放在了implicitModel中。
2.解析请求处理器的目标参数,实际上该目标参数来自于WebDataBinder对象的target属性
1).创建WebDataBinder对象:
①.确定objectName属性:若传入的attrName属性为"",则objectName为类名第一个字母小写。
*注意:attrName.若目标方法的POJO属性使用了@ModelAtrribute来修饰,则attrName值即为@ModelAttibute的value属性值。如:
public String testModelAttribute(@ModelAttribute("user") User user)
②确定target属性;
>在implicitModel中查找attrName对应的属性值。若存在,ok.
>*若不存在:则验证当前Handler是否使用了@SessionAttributes进行修饰,若使用了,则尝试从Session中获取attrName所对应的属性值。若session中没有对应属性值,则抛出异常。
>若Handler没有使用@SessionAtrributes进行修饰,或@SessionAttributes中没有使用value值指定的key和attrName相匹配,则通过反射创建POJO对象。
2).SpringMVC把请求表单的请求参数赋给了WebDataBinder的target对应的属性
3).*SpringMVC会把WebDataBinder的attrName和target给到implicitModel,进而传到request域对象中
4).把WebDataBinder的target作为参数传递给目标方法的入参。
三.SpringMVC确定目标方法POJO类型入参的过程
1.确定一个key:
1)若目标方法的POJO类型的参数没有使用@ModelAttribute作为修饰,则key为POJO类名第一个字母小写。
2)若使用了@ModelAttribute来修饰,则key为@ModelAttribute注解的value属性值。
2.在ImplicitModel中查找key对应的对象,若存在,则作为入参传入
1)若在@ModelAttribute标记的方法中在Map中保存过,且key和1确定的key一直,则会获取到。
3.若implicitModel中不存在对应的对象,则检查当前的Handler是否使用@SessionAttributes注解修饰,若使用了该注解,且@SessionAttributes注解的value属性值中包含了key,则会从HttpSession中来获取key所对应的value值,若存在则直接传入到目标方法的入参中,若不存在则抛出异常。
4.若Handler没有标识@SessionAttributes注解或@SessionAttributes注解的value值不包含key,则会通过反射来创建POJO类型的参数,传入为目标方法的参数。
5.SpringMVC会把key和value保存到implicitModel中,进而会保存到request中。
*/
@ModelAttribute
public void getUser(@RequestParam(value="id",required=false) Integer id,
Map<String,Object> map){
System.out.println("ModelAttribute method");
if(id!=null){
//模拟从数据库中获取对象
User user=new User(1,"Tom,"123456","tom@atguigu.com",12);
System.out.println("从数据库中获取一个对象:" +user);
map.put("user",user);
}
}
@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user){
System.out.println("修改:"+user);
return "success";
}
}
View Code
五、视图相关
1. mvc:view-controller (配置直接转发的页面)
可以直接转发相应的页面,而无需再经过Handler,在实际开发中通常都需要与 mvc:annotation-driven标签相结合,不然@requestMaping会失效


<!--配置直接转发的页面-->
<!--可以直接转发相应的页面,而无需再经过Handler的方法。-->
<mvc:view-controller path"/success" view-name="success" />
<!-- 在实际开发中通常都需要配置mvc:annotation-driven标签-->
<mvc:annotation-driven></mvc:annotation-driven>
View Code
3.@RequestBody
该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上
4.@ResponseBody
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区
5.@ModelAttribute
在方法定义上使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法
在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 –绑定到对象中,再传入入参将方法入参对象添加到模型中
8.@ExceptionHandler
注解到方法上,出现异常时会执行该方法
9.@ControllerAdvice
使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常
四、自动匹配参数
//match automatically
@RequestMapping("/person")
public String toPerson(String name,double age){
System.out.println(name+" "+age);
return "hello";
}
五、自动装箱
1.编写一个Person实体类
package test.SpringMVC.model;
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private String name;
private int age;
}
2.在Controller里编写方法
//boxing automatically
@RequestMapping("/person1")
public String toPerson(Person p){
System.out.println(p.getName()+" "+p.getAge());
return "hello";
}
六、使用InitBinder来处理Date类型的参数
//the parameter was converted in initBinder
@RequestMapping("/date")
public String date(Date date){
System.out.println(date);
return "hello";
}
//At the time of initialization,convert the type "String" to type "date"
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
true));
}
七、向前台传递参数
//pass the parameters to front-end
@RequestMapping("/show")
public String showPerson(Map<String,Object> map){
Person p =new Person();
map.put("p", p);
p.setAge(20);
p.setName("jayjay");
return "show";
}
前台可在Request域中取到"p"
八、使用Ajax调用
//pass the parameters to front-end using ajax
@RequestMapping("/getPerson")
public void getPerson(String name,PrintWriter pw){
pw.write("hello,"+name);
}
@RequestMapping("/name")
public String sayHello(){
return "name";
}
前台用下面的Jquery代码调用
$(function(){
$("#btn").click(function(){
$.post("mvc/getPerson",{name:$("#name").val()},function(data){
alert(data);
});
});
});
九、在Controller中使用redirect方式处理请求
//redirect
@RequestMapping("/redirect")
public String redirect(){
return "redirect:hello";
}
十、文件上传
1.需要导入两个jar包

2.在SpringMVC配置文件中加入
<!-- upload settings -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400000"></property>
</bean>
3.方法代码
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest req) throws Exception{
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
MultipartFile file = mreq.getFile("file");
String fileName = file.getOriginalFilename();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+
"upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
fos.write(file.getBytes());
fos.flush();
fos.close();
return "hello";
}
4.前台form表单
<form action="mvc/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="submit">
</form>
十一、使用@RequestParam注解指定参数的name
@Controller
@RequestMapping("/test")
public class mvcController1 {
@RequestMapping(value="/param")
public String testRequestParam(@RequestParam(value="id") Integer id,
@RequestParam(value="name")String name){
System.out.println(id+" "+name);
return "/hello";
}
}
十二、RESTFul风格的SringMVC
1.RestController
@Controller
@RequestMapping("/rest")
public class RestController {
@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
public String get(@PathVariable("id") Integer id){
System.out.println("get"+id);
return "/hello";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.POST)
public String post(@PathVariable("id") Integer id){
System.out.println("post"+id);
return "/hello";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
public String put(@PathVariable("id") Integer id){
System.out.println("put"+id);
return "/hello";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id){
System.out.println("delete"+id);
return "/hello";
}
}
2.form表单发送put和delete请求
在web.xml中配置
<!-- configure the HiddenHttpMethodFilter,convert the post method to put or delete -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在前台可以用以下代码产生请求
<form action="rest/user/1" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="put">
</form>
<form action="rest/user/1" method="post">
<input type="submit" value="post">
</form>
<form action="rest/user/1" method="get">
<input type="submit" value="get">
</form>
<form action="rest/user/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="delete">
</form>
十三、返回json格式的字符串
1.导入以下jar包

2.方法代码
@Controller
@RequestMapping("/json")
public class jsonController {
@ResponseBody
@RequestMapping("/user")
public User get(){
User u = new User();
u.setId(1);
u.setName("jayjay");
u.setBirth(new Date());
return u;
}
}
十四、异常的处理
1.处理局部异常(Controller内)
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
System.out.println("in testExceptionHandler");
return mv;
}
@RequestMapping("/error")
public String error(){
int i = 5/0;
return "hello";
}
2.处理全局异常(所有Controller)
@ControllerAdvice
public class testControllerAdvice {
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
System.out.println("in testControllerAdvice");
return mv;
}
}
3.另一种处理全局异常的方法
在SpringMVC配置文件中配置
<!-- configure SimpleMappingExceptionResolver -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
</bean>
error是出错页面
十五、设置一个自定义拦截器
1.创建一个MyInterceptor类,并实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("postHandle");
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("preHandle");
return true;
}
}
2.在SpringMVC的配置文件中配置
<!-- interceptor setting -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/mvc/**"/>
<bean class="test.SpringMVC.Interceptor.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
3.拦截器执行顺序

十六、表单的验证(使用Hibernate-validate)及国际化
1.导入Hibernate-validate需要的jar包
(未选中不用导入)

2.编写实体类User并加上验证注解
public class User {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
}
private int id;
@NotEmpty
private String name;
@Past
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
}
ps:@Past表示时间必须是一个过去值
3.在jsp中使用SpringMVC的form表单
<form:form action="form/add" method="post" modelAttribute="user">
id:<form:input path="id"/><form:errors path="id"/><br>
name:<form:input path="name"/><form:errors path="name"/><br>
birth:<form:input path="birth"/><form:errors path="birth"/>
<input type="submit" value="submit">
</form:form>
ps:path对应name
4.Controller中代码
@Controller
@RequestMapping("/form")
public class formController {
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(@Valid User u,BindingResult br){
if(br.getErrorCount()>0){
return "addUser";
}
return "showUser";
}
@RequestMapping(value="/add",method=RequestMethod.GET)
public String add(Map<String,Object> map){
map.put("user",new User());
return "addUser";
}
}
ps:
1.因为jsp中使用了modelAttribute属性,所以必须在request域中有一个"user".
2.@Valid 表示按照在实体上标记的注解验证参数
3.返回到原页面错误信息回回显,表单也会回显
5.错误信息自定义
在src目录下添加locale.properties
NotEmpty.user.name=name can't not be empty
Past.user.birth=birth should be a past value
DateTimeFormat.user.birth=the format of input is wrong
typeMismatch.user.birth=the format of input is wrong
typeMismatch.user.id=the format of input is wrong
在SpringMVC配置文件中配置
<!-- configure the locale resource -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="locale"></property>
</bean>
6.国际化显示
在src下添加locale_zh_CN.properties
locale.properties中添加
username=user name
password=password
创建一个locale.jsp
<body>
<fmt:message key="username"></fmt:message>
<fmt:message key="password"></fmt:message>
</body>
在SpringMVC中配置
<!-- make the jsp page can be visited -->
<mvc:view-controller path="/locale" view-name="locale"/>
让locale.jsp在WEB-INF下也能直接访问
最后,访问locale.jsp,切换浏览器语言,能看到账号和密码的语言也切换了
十七、压轴大戏--整合SpringIOC和SpringMVC
1.创建一个test.SpringMVC.integrate的包用来演示整合,并创建各类

2.User实体类
public class User {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
}
private int id;
@NotEmpty
private String name;
@Past
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
}
3.UserService类
@Component
public class UserService {
public UserService(){
System.out.println("UserService Constructor...\n\n\n\n\n\n");
}
public void save(){
System.out.println("save");
}
}
4.UserController
@Controller
@RequestMapping("/integrate")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user")
public String saveUser(@RequestBody @ModelAttribute User u){
System.out.println(u);
userService.save();
return "hello";
}
}
5.Spring配置文件
在src目录下创建SpringIOC的配置文件applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
>
<context:component-scan base-package="test.SpringMVC.integrate">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
</beans>
在Web.xml中添加配置
<!-- configure the springIOC -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
6.在SpringMVC中进行一些配置,防止SpringMVC和SpringIOC对同一个对象的管理重合
<!-- scan the package and the sub package -->
<context:component-scan base-package="test.SpringMVC.integrate">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
十八、SpringMVC详细运行流程图

十九、SpringMVC运行原理
1. 客户端请求提交到DispatcherServlet
2. 由DispatcherServlet控制器查询一个或多个HandlerMapping,找到处理请求的Controller
3. DispatcherServlet将请求提交到Controller
4. Controller调用业务逻辑处理后,返回ModelAndView
5. DispatcherServlet查询一个或多个ViewResoler视图解析器,找到ModelAndView指定的视图
6. 视图负责将结果显示到客户端
二十、SpringMVC与struts2的区别
1、springmvc基于方法开发的,struts2基于类开发的。springmvc将url和controller里的方法映射。映射成功后springmvc生成一个Handler对象,对象中只包括了一个method。方法执行结束,形参数据销毁。springmvc的controller开发类似web service开发。
2、springmvc可以进行单例开发,并且建议使用单例开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例。
3、经过实际测试,struts2速度慢,在于使用struts标签,如果使用struts建议使用jstl。