还是先从配置入手
web.xml需要配置springMVC的servlet(DispatcherServlet)
springMVC有自己单独的配置文件(与spring配置文件形成继承关系)
springMVC配置文件中都需要配置什么呢?至少有以下两者:
扫描注解@Controller和@ControllerAdvice
http响应消息自动转换配置,用到的类:StringHttpMessageConverter,MappingJackson2HttpMessageConverter。(想一下两个类都什么作用)
不想使用公司内部组件,我选择了轻量级的开源的tomcat作为server,启动成功后,自动跳转到src/main/webapp/index.jsp页面。
SpringMVC注解繁多,使用此框架要频繁和注解打交道。
首先要有一个类用来处理请求,这需要 @Controller来表示这个类。
我们知道HTTP协议的格式,有请求方法,URL,Accept,Content-Type等配置,这些从哪里配置呢?@RequestMapping
除此之外,就是参数。怎样把参数转换成Java对象呢?
常见的注解有 @RequestParam和 @RequestBody。
前者用来处理application/x-www-form-urlencoded编码的内容,GET/POST方法均可。
后者只能处理POST请求的body内的数据,但不能处理application/x-www-form-urlencoded。请参考官方文档:
Annotation indicating a method parametershould be bound to thebody of the web request.
The body of the request is passed through an {@linkHttpMessageConverter} to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with {@code @Valid}.
这段文档准确说清了后者的功能,把方法对象和HTTP请求的body绑定起来。为什么没有GET请求呢,因为GET请求没有body,它的参数通过url传递。
在Content-Type: application/x-www-form-urlencoded的请求中,
get 方式中queryString的值,和post方式中 body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。
总结如下:
在GET请求中,不能使用@RequestBody。
在POST请求,可以使用@RequestBody和@RequestParam,如果使用@RequestBody,对于参数转化的配置必须统一,两者不能同时使用。
继续深挖,Java对象和请求body的转换时怎样完成的呢?是依赖HttpMessageConverter。
Strategy interface that specifies a converter that can convert from and to HTTP requests and responses.
通过文档可知这种转换是双向的。
在上上段文档中,我们还看到了请求参数的另一个需要注意的地方,就是校验。
校验的注解有
除了上面的
@ControllerAdvice :处理兜底异常
@ExceptionHandler :兜底异常处理
@RequestMapping:映射URL,HTTP方法,Content-Type等
@RequestBody:
@ResponseBody和
这篇文章写得很辛苦,测试,读书都是为了准确而深入的认识。
待续……