1. SpringMVC_概述
2. SpringMVC_HelloWorld
(@RequestMapping注解(web.xml中配置DispatcherServlet,init-param初始化参数,初始化springmvc的配置文件,。也可以不配置要使用默认的配置文件与位置/WEB-INF/dispatcherServlet-servlet.xml与servlet-name对应。href=”helloworld”发送helloWorld请求,@RequestMapping来映射请求的url,会被servlet拦截。Springmvc.xml配置视图解析器,把handler方法返回值转为实际的物理视图,InternalResourceViewResolver,配置前缀prefix和后缀suffix。)&)
3. SpringMVC_RequestMapping_修饰类
(@RequestMapping注解简介(href=”spring/test” @RequestMapping(“/spring”))&)
4. SpringMVC_RequestMapping_请求方式
(@RequestMapping和@RequestParam注解的使用(method=RequestMethod.POST指定请求方式,href默认get请求,form表单 method=”POST” action=”spring/test” 通过submit实现post请求) &)
package com.atguigu.springmvc.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.atguigu.springmvc.crud.dao.EmployeeDao;
import com.atguigu.springmvc.crud.entities.Employee;
@Controller
public class SpringMVCTest {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private ResourceBundleMessageSource messageSource;
@RequestMapping("/testSimpleMappingExceptionResolver")
public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
String [] vals = new String[10];
System.out.println(vals[i]);
return "success";
}
@RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
public String testDefaultHandlerExceptionResolver(){
System.out.println("testDefaultHandlerExceptionResolver...");
return "success";
}
@ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND)
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
if(i == 13){
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver...");
return "success";
}
// @ExceptionHandler({RuntimeException.class})
// public ModelAndView handleArithmeticException2(Exception ex){
// System.out.println("[出异常了]: " + ex);
// ModelAndView mv = new ModelAndView("error");
// mv.addObject("exception", ex);
// return mv;
// }
/**
* 1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
* 2. @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
* 3. @ExceptionHandler 方法标记的异常有优先级的问题.
* 4. @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常,
* 则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常.
*/
// @ExceptionHandler({ArithmeticException.class})
// public ModelAndView handleArithmeticException(Exception ex){
// System.out.println("出异常了: " + ex);
// ModelAndView mv = new ModelAndView("error");
// mv.addObject("exception", ex);
// return mv;
// }
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
System.out.println("result: " + (10 / i));
return "success";
}
@RequestMapping("/testFileUpload")
public String testFileUpload(@RequestParam("desc") String desc,
@RequestParam("file") MultipartFile file) throws IOException{
System.out.println("desc: " + desc);
System.out.println("OriginalFilename: " + file.getOriginalFilename());
System.out.println("InputStream: " + file.getInputStream());
return "success";
}
@RequestMapping("/i18n")
public String testI18n(Locale locale){
String val = messageSource.getMessage("i18n.user", null, locale);
System.out.println(val);
return "i18n";
}
@RequestMapping("/testResponseEntity")
public ResponseEntity testResponseEntity(HttpSession session) throws IOException{
byte [] body = null;
ServletContext servletContext = session.getServletContext();
InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
body = new byte[in.available()];
in.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=abc.txt");
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity response = new ResponseEntity(body, headers, statusCode);
return response;
}
@ResponseBody
@RequestMapping("/testHttpMessageConverter")
public String testHttpMessageConverter(@RequestBody String body){
System.out.println(body);
return "helloworld! " + new Date();
}
@ResponseBody
@RequestMapping("/testJson")
public Collection testJson(){
return employeeDao.getAll();
}
@RequestMapping("/testConversionServiceConverer")
public String testConverter(@RequestParam("employee") Employee employee){
System.out.println("save: " + employee);
employeeDao.save(employee);
return "redirect:/emps";
}
}
5. SpringMVC_RequestMapping_请求参数&请求头
(指定控制器方法参数(@RequestMapping(value=”testParam”,params={“username”,”age!=10”}),请求必须包含usernae并且age不能为10)&)
package com.atguigu.springmvc.views;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;
@Component
public class HelloView implements View{
@Override
public String getContentType() {
return "text/html";
}
@Override
public void render(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.getWriter().print("hello view, time: " + new Date());
}
}
6. SpringMVC_RequestMapping_Ant 路径
(使用Ant辅助Web应用程序开发(?匹配一个字符 *匹配任意字符 **匹配多层路径@RequestMapping(“/testAntPath/*/abc”))&)
7. SpringMVC_RequestMapping_PathVariable注解
(@PathVariable注解(可以绑定url里的占位符,@RequestMapping(/testPathVariable/{id} @PathVariable(“id”) Integer id ,占位符的名字要和@PathVariable里面的id必须一致))&)
package com.atguigu.springmvc.handlers;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.atguigu.springmvc.entities.User;
@SessionAttributes(value={"user"}, types={String.class})
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
private static final String SUCCESS = "success";
@RequestMapping("/testRedirect")
public String testRedirect(){
System.out.println("testRedirect");
return "redirect:/index.jsp";
}
@RequestMapping("/testView")
public String testView(){
System.out.println("testView");
return "helloView";
}
@RequestMapping("/testViewAndViewResolver")
public String testViewAndViewResolver(){
System.out.println("testViewAndViewResolver");
return SUCCESS;
}
/**
* 1. 有 @ModelAttribute 标记的方法, 会在每个目标方法执行之前被 SpringMVC 调用!
* 2. @ModelAttribute 注解也可以来修饰目标方法 POJO 类型的入参, 其 value 属性值有如下的作用:
* 1). SpringMVC 会使用 value 属性值在 implicitModel 中查找对应的对象, 若存在则会直接传入到目标方法的入参中.
* 2). SpringMVC 会一 value 为 key, POJO 类型的对象为 value, 存入到 request 中.
*/
@ModelAttribute
public void getUser(@RequestParam(value="id",required=false) Integer id,
Map 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);
}
}
/**
* 运行流程:
* 1. 执行 @ModelAttribute 注解修饰的方法: 从数据库中取出对象, 把对象放入到了 Map 中. 键为: user
* 2. SpringMVC 从 Map 中取出 User 对象, 并把表单的请求参数赋给该 User 对象的对应属性.
* 3. SpringMVC 把上述对象传入目标方法的参数.
*
* 注意: 在 @ModelAttribute 修饰的方法中, 放入到 Map 时的键需要和目标方法入参类型的第一个字母小写的字符串一致!
*
* 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 中不存在 key 对应的对象, 则检查当前的 Handler 是否使用 @SessionAttributes 注解修饰,
* 若使用了该注解, 且 @SessionAttributes 注解的 value 属性值中包含了 key, 则会从 HttpSession 中来获取 key 所
* 对应的 value 值, 若存在则直接传入到目标方法的入参中. 若不存在则将抛出异常.
* 4. 若 Handler 没有标识 @SessionAttributes 注解或 @SessionAttributes 注解的 value 值中不包含 key, 则
* 会通过反射来创建 POJO 类型的参数, 传入为目标方法的参数
* 5. SpringMVC 会把 key 和 POJO 类型的对象保存到 implicitModel 中, 进而会保存到 request 中.
*
* 源代码分析的流程
* 1. 调用 @ModelAttribute 注解修饰的方法. 实际上把 @ModelAttribute 方法中 Map 中的数据放在了 implicitModel 中.
* 2. 解析请求处理器的目标参数, 实际上该目标参数来自于 WebDataBinder 对象的 target 属性
* 1). 创建 WebDataBinder 对象:
* ①. 确定 objectName 属性: 若传入的 attrName 属性值为 "", 则 objectName 为类名第一个字母小写.
* *注意: attrName. 若目标方法的 POJO 属性使用了 @ModelAttribute 来修饰, 则 attrName 值即为 @ModelAttribute
* 的 value 属性值
*
* ②. 确定 target 属性:
* > 在 implicitModel 中查找 attrName 对应的属性值. 若存在, ok
* > *若不存在: 则验证当前 Handler 是否使用了 @SessionAttributes 进行修饰, 若使用了, 则尝试从 Session 中
* 获取 attrName 所对应的属性值. 若 session 中没有对应的属性值, 则抛出了异常.
* > 若 Handler 没有使用 @SessionAttributes 进行修饰, 或 @SessionAttributes 中没有使用 value 值指定的 key
* 和 attrName 相匹配, 则通过反射创建了 POJO 对象
*
* 2). SpringMVC 把表单的请求参数赋给了 WebDataBinder 的 target 对应的属性.
* 3). *SpringMVC 会把 WebDataBinder 的 attrName 和 target 给到 implicitModel.
* 近而传到 request 域对象中.
* 4). 把 WebDataBinder 的 target 作为参数传递给目标方法的入参.
*/
@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user){
System.out.println("修改: " + user);
return SUCCESS;
}
/**
* @SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外(实际上使用的是 value 属性值),
* 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上使用的是 types 属性值)
*
* 注意: 该注解只能放在类的上面. 而不能修饰放方法.
*/
@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Map map){
User user = new User("Tom", "123456", "tom@atguigu.com", 15);
map.put("user", user);
map.put("school", "atguigu");
return SUCCESS;
}
/**
* 目标方法可以添加 Map 类型(实际上也可以是 Model 类型或 ModelMap 类型)的参数.
* @param map
* @return
*/
@RequestMapping("/testMap")
public String testMap(Map map){
System.out.println(map.getClass().getName());
map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
return SUCCESS;
}
/**
* 目标方法的返回值可以是 ModelAndView 类型。
* 其中可以包含视图和模型信息
* SpringMVC 会把 ModelAndView 的 model 中数据放入到 request 域对象中.
* @return
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String viewName = SUCCESS;
ModelAndView modelAndView = new ModelAndView(viewName);
//添加模型数据到 ModelAndView 中.
modelAndView.addObject("time", new Date());
return modelAndView;
}
/**
* 可以使用 Serlvet 原生的 API 作为目标方法的参数 具体支持以下类型
*
* HttpServletRequest
* HttpServletResponse
* HttpSession
* java.security.Principal
* Locale InputStream
* OutputStream
* Reader
* Writer
* @throws IOException
*/
@RequestMapping("/testServletAPI")
public void testServletAPI(HttpServletRequest request,
HttpServletResponse response, Writer out) throws IOException {
System.out.println("testServletAPI, " + request + ", " + response);
out.write("hello springmvc");
// return SUCCESS;
}
/**
* Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配, 自动为该对象填充属性值。支持级联属性。
* 如:dept.deptId、dept.address.tel 等
*/
@RequestMapping("/testPojo")
public String testPojo(User user) {
System.out.println("testPojo: " + user);
return SUCCESS;
}
/**
* 了解:
*
* @CookieValue: 映射一个 Cookie 值. 属性同 @RequestParam
*/
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) {
System.out.println("testCookieValue: sessionId: " + sessionId);
return SUCCESS;
}
/**
* 了解: 映射请求头信息 用法同 @RequestParam
*/
@RequestMapping("/testRequestHeader")
public String testRequestHeader(
@RequestHeader(value = "Accept-Language") String al) {
System.out.println("testRequestHeader, Accept-Language: " + al);
return SUCCESS;
}
/**
* @RequestParam 来映射请求参数. value 值即请求参数的参数名 required 该参数是否必须. 默认为 true
* defaultValue 请求参数的默认值
*/
@RequestMapping(value = "/testRequestParam")
public String testRequestParam(
@RequestParam(value = "username") String un,
@RequestParam(value = "age", required = false, defaultValue = "0") int age) {
System.out.println("testRequestParam, username: " + un + ", age: "
+ age);
return SUCCESS;
}
/**
* Rest 风格的 URL. 以 CRUD 为例: 新增: /order POST 修改: /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
*
* 在 SpringMVC 的目标方法中如何得到 id 呢? 使用 @PathVariable 注解
*
*/
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
public String testRestPut(@PathVariable Integer id) {
System.out.println("testRest Put: " + id);
return SUCCESS;
}
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
public String testRestDelete(@PathVariable Integer id) {
System.out.println("testRest Delete: " + id);
return SUCCESS;
}
@RequestMapping(value = "/testRest", method = RequestMethod.POST)
public String testRest() {
System.out.println("testRest POST");
return SUCCESS;
}
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
public String testRest(@PathVariable Integer id) {
System.out.println("testRest GET: " + id);
return SUCCESS;
}
/**
* @PathVariable 可以来映射 URL 中的占位符到目标方法的参数中.
* @param id
* @return
*/
@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id) {
System.out.println("testPathVariable: " + id);
return SUCCESS;
}
@RequestMapping("/testAntPath/*/abc")
public String testAntPath() {
System.out.println("testAntPath");
return SUCCESS;
}
/**
* 了解: 可以使用 params 和 headers 来更加精确的映射请求. params 和 headers 支持简单的表达式.
*
* @return
*/
@RequestMapping(value = "testParamsAndHeaders", params = { "username",
"age!=10" }, headers = { "Accept-Language=en-US,zh;q=0.8" })
public String testParamsAndHeaders() {
System.out.println("testParamsAndHeaders");
return SUCCESS;
}
/**
* 常用: 使用 method 属性来指定请求方式
*/
@RequestMapping(value = "/testMethod", method = RequestMethod.POST)
public String testMethod() {
System.out.println("testMethod");
return SUCCESS;
}
/**
* 1. @RequestMapping 除了修饰方法, 还可来修饰类 2. 1). 类定义处: 提供初步的请求映射信息。相对于 WEB 应用的根目录
* 2). 方法处: 提供进一步的细分映射信息。 相对于类定义处的 URL。若类定义处未标注 @RequestMapping,则方法处标记的 URL
* 相对于 WEB 应用的根目录
*/
@RequestMapping("/testRequestMapping")
public String testRequestMapping() {
System.out.println("testRequestMapping");
return SUCCESS;
}
}
8. SpringMVC_HiddenHttpMethodFilter 过滤器
(@RestController注解(web.xml里设置过滤器,hIddenHttpMethodFilter可以把Post请求转为PUT请求或者Delete请求)&)
package com.atguigu.springmvc.handlers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorld {
/**
* 1. 使用 @RequestMapping 注解来映射请求的 URL
* 2. 返回值会通过视图解析器解析为实际的物理视图, 对于 InternalResourceViewResolver 视图解析器, 会做如下的解析:
* 通过 prefix + returnVal + 后缀 这样的方式得到实际的物理视图, 然会做转发操作
*
* /WEB-INF/views/success.jsp
*
* @return
*/
@RequestMapping("/helloworld")
public String hello(){
System.out.println("hello world");
return "success";
}
}
9. SpringMVC_RequestParam 注解
(@GPRequestParam(请求参数href=”springmvc/testRequestParam?username=at&age=11”,使用@RequestParam(value=”username”,required=false,defaultValue=”9”) String un,Integer age)来获取请求参数值,不是必须的参数值,defaultValue绑定默认值接收int类型的值)&)
10. SpringMVC_RequestHeader 注解
(ngx_http_send_header(@RequestHeader(value=”Accept-Language” String al)接收请求头数据) &)
11. SpringMVC_CookieValue 注解
(http和cookie身份验证模式(@cookieValue(“JSESSIONID”) string sessionId 获取sessionId)&)
12. SpringMVC_使用POJO作为参数
(激发POJO的潜能(表单对应一个映射,通过java对象作为请求参数,testPojo(User user) ,级联属性表单通过 name=”address.id”)&)
13. SpringMVC_使用Servlet原生API作为参数
(通过HttpServletRequest接收请求参数(test(HttpServletRequest request,HttpServletResponse resp) )&)
14. SpringMVC_处理模型数据之ModelAndView
(方法返回值是ModelAndView数据类型(ModelAndView做为返回值,addObject(“time”) 前端获取值 ${requestScope.time} )&)
15 SpringMVC_处理模型数据之Map
(Map(入参可以加入Map类型的参数,Map map 前台同样可以获取请求域里的值${requestScope,names} )&)
16. SpringMVC_处理模型数据之 SessionAttributes 注解
(@SessionAttribute注解(放在session中,@SessionAttributes({user} type=”String.class”) 放在类上,对应模型中的user,这样可以把数据既放在请求域中,也可以放在session域中,并把指定类型的值也放在session中)&)
17. SpringMVC_ModelAttribute注解之使用场景
dispatcherServlet-servlet.xml
web.xml
HiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
HiddenHttpMethodFilter
/*
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
1
dispatcherServlet
/
success.jsp
Insert title here
Sucess Page
time: ${requestScope.time }
names: ${requestScope.names }
request user: ${requestScope.user }
session user: ${sessionScope.user }
request school: ${requestScope.school }
session school: ${sessionScope.school }
abc user: ${requestScope.abc }
mnxyz user: ${requestScope.mnxyz }
index.jsp
Insert title here
Test Redirect
Test View
Test ViewAndViewResolver
username:
email:
age:
Test SessionAttributes
Test Map
Test ModelAndView
Test ServletAPI
username:
password:
email:
age:
city:
province:
Test CookieValue
Test RequestHeader
Test RequestParam
Test Rest Get
Test PathVariable
Test AntPath
Test ParamsAndHeaders
Test Method
Test RequestMapping
Hello World
18. SpringMVC_ModelAttribute注解之示例代码
(@RequestParam注解(密码不可被修改,@RequestParam(value=”id”,required=false) if(id!=null){ } @ModelAttribute注解标记的方法,会在每个目标方法执行之前被springmvc调用,传入参数的部分属性,执行@ModelAndView修饰的方法,会把对象存入Map中,键为user,之后springMVC会把表单请求参数赋给该User对应属性(键要与对应参数的值(类名小写)一致),最后注入到目标方法的参数中)&)
19. SpringMVC_ModelAttribute注解之运行原理
20. SpringMVC_ModelAttribute注解之源码分析
21. SpringMVC_如何确定目标方法POJO类型参数
(@ModelAttribute注解(map.put(“abc”,user) test(@ModelAndView(‘abc”) User user) ${requestScope.abc} 请求域中获取对应,不添加ModelAndView默认的key是类名小写)&)
22. SpringMVC_ModelAttribute注解修饰POJO类型的入参
(@ModelAttribute注解()&)
23. SpringMVC_SessionAttributes注解引发的异常
(使用 @SessionAttributes注解&(确定目标方法pojo的入参,先看@ModelAndView表示的方法,如果没有回去@SessionAttributes寻找对应的内容,))
24. SpringMVC_视图解析流程分析
(视图和视图解析器(视图解析流程,InternalResourceViewResolve目的是把逻辑视图转为物理视图,把返回值转为ModelAndView类型,根据视图解析器ViewResolver解析视图转为真正的物理视图,获得视图之后渲染视图view.render(),视图是无状态的每一个请求都会获得一个新的视图所以不会有线程安全问题)&)
web.xml
springDispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
1
springDispatcherServlet
/
HiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
HiddenHttpMethodFilter
/*
list.jsp
Insert title here
$(function(){
$(".delete").click(function(){
var href = $(this).attr("href");
$("form").attr("action", href).submit();
return false;
});
})
没有任何员工信息.
ID
LastName
Email
Gender
Department
Edit
Delete
${emp.id }
${emp.lastName }
${emp.email }
${emp.gender == 0 ? 'Female' : 'Male' }
${emp.department.departmentName }
Edit
Delete
Add New Employee
success.jsp
Insert title here
Success Page
i18n.jsp
Insert title here
I18N2 PAGE
中文
英文
i18n2.jsp
Insert title here
I18N PAGE
input.jsp
Insert title here
Employee:
LastName:
Email:
Gender:
Department:
Birth:
Salary:
error.jsp
Insert title here
Error Page
${requestScope.exception }
25. SpringMVC_JstlView
(ResourceBundleViewResolver(配置国际化资源,ResourceBundlerMessageSource base)&)
26. SpringMVC_mvc_view-controller标签
( iView经典组件剖析(配置直接转发的映射 ,直接跳转页面不会经过handler,通过都要加入mvc:annotation-driven标签)&)
27. SpringMVC_自定义视图
(BeanNameViewResolver (自定义视图 implements View ,order 定义视图解析器的优先级,值越小优先级越高)&)
28. SpringMVC_重定向
( redirect标签(重定向,forward:执行转发操作,redirect:执行重定向操作)&)
29. SpringMVC_RESTRUL_CRUD_需求
30. SpringMVC_RESTRUL_CRUD_显示所有员工信息
(多线程版本的(if(,${emp.gender == 0?’Female’:’Male’}})&)
31. SpringMVC_RESTRUL_CRUD_添加操作&表单标签
(Request类&表单标签的应用&)
32. SpringMVC_RESTRUL_CRUD_删除操作&处理静态资源
(pageContext&静态资源配置(处理静态资源,通过Rest请求资源,配置mvc:default-servlet-handler)&)
33. SpringMVC_RESTRUL_CRUD_修改操作
(使用@ModelAttribute访问模型数据( form:form modelAttribute = “employee” 的值必须有后台map中的key对应一致)&绝对路径与相对路径(action=”${pageContext.request.contextPath}/emp” 前台都要加上绝对路径)&)
34. SpringMVC_数据绑定流程分析
(数据绑定(springMVC会将目标对象的方法参数实例传递给WebDataBinderFactory实例,创建DataBinder实例对象,之后调用ConversionService组件进行数据类型转换、数据格式化工作,)&)
package com.atguigu.springmvc.crud.handlers;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.atguigu.springmvc.crud.dao.DepartmentDao;
import com.atguigu.springmvc.crud.dao.EmployeeDao;
import com.atguigu.springmvc.crud.entities.Employee;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
@ModelAttribute
public void getEmployee(@RequestParam(value="id",required=false) Integer id,
Map map){
if(id != null){
map.put("employee", employeeDao.get(id));
}
}
@RequestMapping(value="/emp", method=RequestMethod.PUT)
public String update(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
@RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
public String input(@PathVariable("id") Integer id, Map map){
map.put("employee", employeeDao.get(id));
map.put("departments", departmentDao.getDepartments());
return "input";
}
@RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}
@RequestMapping(value="/emp", method=RequestMethod.POST)
public String save(@Valid Employee employee, Errors result,
Map map){
System.out.println("save: " + employee);
if(result.getErrorCount() > 0){
System.out.println("出错了!");
for(FieldError error:result.getFieldErrors()){
System.out.println(error.getField() + ":" + error.getDefaultMessage());
}
//若验证出错, 则转向定制的页面
map.put("departments", departmentDao.getDepartments());
return "input";
}
employeeDao.save(employee);
return "redirect:/emps";
}
@RequestMapping(value="/emp", method=RequestMethod.GET)
public String input(Map map){
map.put("departments", departmentDao.getDepartments());
map.put("employee", new Employee());
return "input";
}
@RequestMapping("/emps")
public String list(Map map){
map.put("employees", employeeDao.getAll());
return "list";
}
// @InitBinder
// public void initBinder(WebDataBinder binder){
// binder.setDisallowedFields("lastName");
// }
}
package com.atguigu.springmvc.crud.entities;
import java.util.Date;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
public class Employee {
private Integer id;
@NotEmpty
private String lastName;
@Email
private String email;
//1 male, 0 female
private Integer gender;
private Department department;
@Past
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
@NumberFormat(pattern="#,###,###.#")
private Float salary;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", department=" + department
+ ", birth=" + birth + ", salary=" + salary + "]";
}
public Employee(Integer id, String lastName, String email, Integer gender,
Department department) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
}
public Employee() {
// TODO Auto-generated constructor stub
}
}
package com.atguigu.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.atguigu.springmvc.crud.entities.Department;
import com.atguigu.springmvc.crud.entities.Employee;
@Repository
public class EmployeeDao {
private static Map employees = null;
@Autowired
private DepartmentDao departmentDao;
static{
employees = new HashMap();
employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
}
private static Integer initId = 1006;
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
public Collection getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
package com.atguigu.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.atguigu.springmvc.crud.entities.Department;
@Repository
public class DepartmentDao {
private static Map departments = null;
static{
departments = new HashMap();
departments.put(101, new Department(101, "D-AA"));
departments.put(102, new Department(102, "D-BB"));
departments.put(103, new Department(103, "D-CC"));
departments.put(104, new Department(104, "D-DD"));
departments.put(105, new Department(105, "D-EE"));
}
public Collection getDepartments(){
return departments.values();
}
public Department getDepartment(Integer id){
return departments.get(id);
}
}
35. SpringMVC_自定义类型转换器
(一对一转换器(Converter)(ConversionService是Spring类型转换的核心接口,test(@RequestParam(“employee”) Employee employee) ,name=”employee” 把字符串转为employee对象, implements Converter convert(){ },把cpversopService注入到annotation-driven中 conversion-service中)&)
36. SpringMVC_annotation-driven配置
(走向注解驱动编程(Annotation-Driven)( 会自动注册RequestMappingHandlerMapping,HandlerAdapter和ExceptionResolver三个bean,支持@NumberFormat,@DateTimeFormat,@Valid以及@ResponseBody和@RequestBody注解的使用)&)
37. SpringMVC_InitBinder注解
(示例:使用@InitBinder添加自定义编辑器转换数据(@InitBinder对WebDataBinder对象绑定,完成表单字段到JavaBean属性的绑定,对多选角色)&)
38. SpringMVC_数据的格式化
(日期与时间(date、time、datetime、timestamp)(@DateTimeFormat(pattern=”yyyy-mm-dd”),@NumberFormat(pattern=”#,###,###.#”))&binding元素(类型转换异常,异常信息会放在BindingResult中)&)
39. SpringMVC_JSR303数据校验
(JSR303验证(@NotEmpty @Past test(@Valid Employee employee))&)
40. SpringMVC_错误消息的显示及国际化
(错误处理(页面显示错误消息 * 显示所有的错误消息)&)
41. SpringMVC_返回JSON
(@ResponseBody注解(@RequestBody注解返回Json字符串数组,通过.获取json对象中的值)&)
42. SpringMVC_HttpMessageConverter原理
(HttpMessageConverter接口()&)
43. SpringMVC_使用HttpMessageConverter
(@RequestBody返回JSON格式的数据(@RequestBody对入参修改,@ResponseBody对方法进行修饰没有页码对应直接转为输出流响应客户端,enctype=”multipart/form-data ” 文件下载ResponseBodyEntity 对文件进行下载处理,session.getServletContext(); in=servletContext.getResourceAsStream(“/files/abc.txt”) 读取webContext目录下的文件,)&)
package com.atguigu.springmvc.converters;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import com.atguigu.springmvc.crud.entities.Department;
import com.atguigu.springmvc.crud.entities.Employee;
@Component
public class EmployeeConverter implements Converter {
@Override
public Employee convert(String source) {
if(source != null){
String [] vals = source.split("-");
//GG-gg@atguigu.com-0-105
if(vals != null && vals.length == 4){
String lastName = vals[0];
String email = vals[1];
Integer gender = Integer.parseInt(vals[2]);
Department department = new Department();
department.setId(Integer.parseInt(vals[3]));
Employee employee = new Employee(null, lastName, email, gender, department);
System.out.println(source + "--convert--" + employee);
return employee;
}
}
return null;
}
}
44. SpringMVC_国际化_概述
( ResourceBundle类()&)
45. SpringMVC_国际化_前两个问题
(创建国际化的Web 应用(ResourceBundleMessageSource指向i18n.properties文件,获取国际化资源的值,通过ResourceBundleMessageSource.getMessage来获取)&)
46. SpringMVC_国际化_通过超链接切换Locale
(<fmt:message>标签(通过SessionLocaleResolver不依赖浏览器语言的设置国际化,)&)
i18n.properties
i18n.username=Username
i18n.password=Password
i18n_en_US.properties
i18n.username=Username
i18n.password=Password
i18n_zh_CN.properties
i18n.username=\u7528\u6237\u540D
i18n.password=\u5BC6\u7801
47. SpringMVC_文件上传
(MultipartResolver (通过MultipartResolver实现文件上传,在配置文件中配置该接口的实现类,test(@RequestParam(“file”) MultipartFile file){ } 通过表单对应的name上传文件,file.getInputStream获取输入流。)&)
48. SpringMVC_第一个自定义的拦截器
(HandlerInterceptor接口(自定义拦截器实现HandlerInterceptor接口,preHandler目标方法之前调用如果true则调用后序的方法与拦截器,与postHandler和afterCompletion渲染视图之后调用,在配置文件中mvc:interceptor中配置自定义拦截器,对日志权限事务进行处理)&)
49. SpringMVC_拦截器的配置
(拦截器定义与配置(mvc:mapping path=”/emps/”)设置拦截器作用路径,&)
50. SpringMVC_多个拦截器方法的执行顺序
(拦截器链(多个拦截器执行顺序,如果preHandler执行false直接调用afterCopletion)&)
package com.atguigu.springmvc.interceptors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class FirstInterceptor implements HandlerInterceptor{
/**
* 该方法在目标方法之前被调用.
* 若返回值为 true, 则继续调用后续的拦截器和目标方法.
* 若返回值为 false, 则不会再调用后续的拦截器和目标方法.
*
* 可以考虑做权限. 日志, 事务等.
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("[FirstInterceptor] preHandle");
return true;
}
/**
* 调用目标方法之后, 但渲染视图之前.
* 可以对请求域中的属性或视图做出修改.
*/
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("[FirstInterceptor] postHandle");
}
/**
* 渲染视图之后被调用. 释放资源
*/
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("[FirstInterceptor] afterCompletion");
}
}
package com.atguigu.springmvc.interceptors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class SecondInterceptor implements HandlerInterceptor{
/**
* 该方法在目标方法之前被调用.
* 若返回值为 true, 则继续调用后续的拦截器和目标方法.
* 若返回值为 false, 则不会再调用后续的拦截器和目标方法.
*
* 可以考虑做权限. 日志, 事务等.
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("[SecondInterceptor] preHandle");
return false;
}
/**
* 调用目标方法之后, 但渲染视图之前.
* 可以对请求域中的属性或视图做出修改.
*/
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("[SecondInterceptor] postHandle");
}
/**
* 渲染视图之后被调用. 释放资源
*/
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("[SecondInterceptor] afterCompletion");
}
}
51. SpringMVC_异常处理_ExceptionHandler注解
(示例:@ExceptionHandler处理异常(@ExceptionHandler({ArtimeticException.class}),要返回异常信息必须返回ModelAndView,默认情况只处理匹配度更高的异常信息,只能处理当前局部的handler异常,@ControllerAdvice可以处理全局异常)&)
52. SpringMVC_异常处理_ResponseStatusExceptionResolver
( @ResponseStatus注解(@ResponseStatus(value=HttpStatus.FORBIDDEN ,reason=””) 定制错误信息)&)
53. SpringMVC_异常处理_DefaultHandlerExceptionResolver
(HandlerExceptionResolver(请求必须是post请求才可以,) &)
54. SpringMVC_异常处理_SimpleMappingExceptionResolver
(SimpleMappingExceptionResolver类(配置SimpleMappingExceptionResolver异常映射,异常发生时对应的页面中异常的回显信息)&)
package com.atguigu.springmvc.test;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class SpringMVCTestExceptionHandler {
@ExceptionHandler({ArithmeticException.class})
public ModelAndView handleArithmeticException(Exception ex){
System.out.println("----> 出异常了: " + ex);
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
}
}
package com.atguigu.springmvc.test;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.FORBIDDEN, reason="用户名和密码不匹配!")
public class UserNameNotMatchPasswordException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
}
55. SpringMVC_运行流程图解
(配置springMVC-servlet.xml文件(根据请求发送过来到达DispatcherServlet与url-pattern对应,如果没有对应映射,如果设置了mvc:default-servlet-handler 会报404,如果有defualt映射会去找目标资源。如果存在由HandlerMapping获取HandlerExecutionChain对象,获取对应的HandlerAdapter适配器,调用preHandler拦截器,之后调用Handler目标方法得到ModelAndView,之后调用POSTHandler方法,还要判断是否有异常,由HandlerExceptionResolver组件处理异常,得到新的ModelAndeView)&)
56. SpringMVC_源码解析
(SpringMVC框架层面的约定和定制&)
57. SpringMVC_Spring整合SpringMVC_提出问题
(Spring4MVC+MyBatis3+Spring4整合(是否需要在web.xml中配置启动IOC容器的ContextLoaderListener,默认数据库事务和整合其他框架和Dao还有Service都放在Spring的配置文件中,也可以通过@Import导入其他的配置文件)&)
58. SpringMVC_Spring整合SpringMVC_解决方案
(开启配置(@Enable*和@Import)(Spring与SpringMVC初始化容器会初始化两边bean,尽量不要有重合的包扫描,可以使用 要扫描的注解,use-default-filters 不再用默认的filter进行扫描)&)
beans.xml
springmvc.xml
package com.atguigu.springmvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private HelloWorld helloWorld;
public UserService() {
System.out.println("UserService Constructor...");
}
}
package com.atguigu.springmvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorld {
@Autowired
private UserService userService;
public HelloWorld() {
System.out.println("HelloWorld Constructor...");
}
@RequestMapping("/helloworld")
public String hello(){
System.out.println("success");
System.out.println(userService);
return "success";
}
}
59. SpringMVC_SpringIOC 容器和 SpringMVC IOC 容器的关系
(IOC容器(springMVC的bean可以引用spring的bean,子容器可以访问父容器的bean)&)
60. SpringMVC_SpringMVC对比Struts2
index.jsp
Insert title here
Hello World
web.xml
contextConfigLocation
classpath:beans.xml
org.springframework.web.context.ContextLoaderListener
springDispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
1
springDispatcherServlet
/
success.jsp
Insert title here
Success Page