详解SpringMVC中Controller的方法中参数的工作原理[附带源码分析](三)

2014-11-23 21:30:58 · 作者: · 浏览: 17
因此选择了ServletModelAttributeMethodProcessor,最终通过DataBinder实例化Employee对象,并写入对应的属性。
3. testCustomObjWithRp方法以及地址 http://localhost:8888/SpringMVCDemo/test/testCustomObjWithRp name=1&age=3
这个请求会找到RequestParamMethodArgumentResolver(使用了@RequestParam注解)。RequestParamMethodArgumentResolver在处理参数的时候使用request.getParameter(参数名)即request.getParameter("e")得到,很明显我们的参数传的是name=1&age=3。因此得到null,RequestParamMethodArgumentResolver处理missing value会触发MissingServletRequestParameterException异常。 [粗略讲下,有兴趣的读者请自行查看源码]
解决方案:去掉@RequestParam注解,让ServletModelAttributeMethodProcessor来处理。
4. testDate方法以及地址 http://localhost:8888/SpringMVCDemo/test/testDate date=2014-05-15
这个请求会找到RequestParamMethodArgumentResolver。因为这个方法与第二个方法一样,有两个RequestParamMethodArgumentResolver,属性useDefaultResolution不同。RequestParamMethodArgumentResolver支持简单类型,ServletModelAttributeMethodProcessor是支持非简单类型。最终步骤跟第三个方法一样,我们的参数名是date,于是通过request.getParameter("date")找到date字符串(这里参数名如果不是date,那么最终页面是空白的,因为没有@RequestParam注解,参数不是必须的,RequestParamMethodArgumentResolver处理null值返回null)。最后通过DataBinder找到合适的属性编辑器进行类型转换。最终找到java.util.Date对象的构造函数 public Date(String s),由于我们传递的格式不是标准的UTC时间格式,因此最终触发了IllegalArgumentException异常。
解决方案:
1. 传递参数的格式修改成标准的UTC时间格式:http://localhost:8888/SpringMVCDemo/test/testDate date=Sat, 17 May 2014 16:30:00 GMT
2.在Controller中加入自定义属性编辑器。
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
这个@InitBinder注解在实例化ServletInvocableHandlerMethod的时候被注入到WebDataBinderFactory中的,而WebDataBinderFactory是ServletInvocableHandlerMethod的一个属性。在RequestMappingHandlerAdapter源码的803行getDataBinderFactory就是得到的WebDataBinderFactory。
之后RequestParamMethodArgumentResolver通过WebDataBinderFactory创建的WebDataBinder里的自定义属性编辑器找到合适的属性编辑器(我们自定义的属性编辑器是用CustomDateEditor处理Date对象,而testDate的参数刚好是Date),最终CustomDateEditor把这个String对象转换成Date对象。
编写自定义的HandlerMethodArgumentResolver
通过前面的分析,我们明白了SpringMVC处理Controller中的方法的参数流程。
现在,如果方法中有两个参数,且都是自定义类参数,那该如何处理呢?
@RequestMapping("/save")
public ModelAndView saveAll(@FormModel Employee employee, @FormModel Dept dept, ModelAndView view) {
view.setViewName("test/success");
view.addObject("employee", employee);
view.addObject("dept", dept);
return view;
}
我们就来试试吧。
很明显,要处理这个只能自己实现一个实现HandlerMethodArgumentResolver的类。