@ResponseBody
注解修饰控制器方法,并在xxx-servlet.xml中开启spring mvc支持——<mvc: annoation-driven/>
,这种机制背后的原理是MessageConverter。ViewResolver的继承体系
<select id="getInPaging" resultType="java.util.List">
<![CDATA[
SELECT
number
FROM
example_table
WHERE
id=#{id}
]]>
</select>
在这里,resultType指的是查询到的每条记录的类型,因此应该用java.lang.String
。
//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));
}
<mvc:annotation-driven>
、@ResponseBody
、HttpMessagerConverter
等的实现原理,SpringMVC关于json、xml自动转换的原理研究[附带源码分析]这篇文章,以及对应的代码分析,基本上都讲清楚了。PS:MappingJackson2HttpMessageConverter和MappingJacksonHttpMessageConverter的区别在于,Spring 4版本都用前一个。mvc-context-hierarchy.png
最后,再重温下spring mvc的处理流程,在进行Java Web开发的时候,也时刻不要忘记对HttpRequest的处理流程。
Spring MVC详细运行流程图.png