SpringMVC-请求参数
一、获取单个参数:
@RequestParam(value = "",required = true,defaultValue = "")
value = "":指定要获取的参数的key
required = true:这个参数是否是必须的
defaultValue = "":默认值,没带默认null
1. @RequestParam():获取请求路径“?”后面参数的值
@RequestMapping("/handle")
public String handle(@RequestParam("name") String name) {
return "" ;
}
2. @PathVariable():获取路径中key的值
@RequestMapping("/handle/{name}")
public String handle(@PathVariable("name") String name) {
return "" ;
}
3. @RequestHeader():获取请求头中某个key的值
@RequestMapping("/handle")
public String handle(@RequestHeader("User-Agent") String userAgent) {
return "" ;
}
4. @CookieValue():
@RequestMapping("/handle")
public String handle(@CookieValue("JESSIONID") String jid) {
return "" ;
}
二、获取vo参数:级联属性也可以封装
@RequestMapping("/handle")
public String handle(Member member) {
return "" ;
}
三、传入原生API:
@RequestMapping("/handle")
public String handle(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
return "" ;
}
虽然方法上可以获取内置对象,但是考虑到其他地方也需要内置对象,可以通过RequestContextHolder获取:
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest() ;
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse() ;
四、请求乱码:
GET请求:在Tomcat中修改server.xml配置文件,在8080端口处设置URIEncoding="UTF-8"
POST请求:在第一次请求之前设置request.setCharacterEncoding("UTF-8"),SpringMVC提供了编码过滤器:CharacterEncodingFilter
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- encoding:解决POST请求乱码 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- :forceEncoding响应乱码 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>