- Summary:
handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类:(主要讲解常用类型)
A、处理requet uri 部分(这里指uri template中variable,不含queryString部分)的注解: @PathVariable;
B、处理request header部分的注解: @RequestHeader, @CookieValue;
C、处理request body部分的注解:@RequestParam, @RequestBody;
D、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;
1. 使用 @PathVariabl 注解获取路径中传递参数5. 使用 @CookieValue 获取 cookie 的值到
2. 使用 @ModelAttribute 注解获取POST请求的FORM表单数据
3. 直接用HttpServletRequest/HttpServletResponse获取数据
4. 使用 @RequestParam 获取 HttpServletRequest 请求参数
6. 使用 @RequestHeader 获取 HttpServletRequest 头信息
7. 使用 @SessionAttributes 获取 HttpSession 信息
- Example:
1. 使用 @PathVariabl 注解获取路径中传递参数
JAVA
@RequestMapping(value = "/{id}/{str}")
public ModelAndView helloWorld(@PathVariable String id, @PathVariable String str) {
System.out.println(id);
System.out.println(str);
return new ModelAndView("/helloWorld");
}2. 使用 @ModelAttribute 注解获取POST请求的FORM表单数据
JSP
<form method="post" action="hao.do">
a: <input id="a" type="text" name="a"/>
b: <input id="b" type="text" name="b"/>
<input type="submit" value="Submit" />
</form>
JAVA pojo
public class Pojo{
private String a;
private int b;
}
JAVA controller
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pojo") Pojo pojo) {
return "helloWorld";
}
3. 直接用HttpServletRequest/HttpServletResponse获取数据
JAVA
@RequestMapping(method = RequestMethod.GET)
public String get(HttpServletRequest request, HttpServletResponse response) {
System.out.println(request.getParameter("a"));
return "helloWorld";
}4. 使用 @RequestParam 获取 HttpServletRequest 请求参数
JAVA
@RequestMapping(value = "/requestParam", method = RequestMethod.GET)
public String setupForm(@RequestParam("a") String a, ModelMap model) {
System.out.println(a);
return "helloWorld";}5. 使用 @CookieValue 获取 cookie 的值到
JAVA
@RequestMapping ( "cookieValue" )
public String testCookieValue( @CookieValue ( "hello" ) String cookieValue, @CookieValue String hello) {
System. out .println(cookieValue + "-----------" + hello);
return "cookieValue" ;
}6. 使用 @RequestHeader 获取 HttpServletRequest 头信息
@RequestMapping ( "testRequestHeader" )
public String testRequestHeader( @RequestHeader ( "Host" ) String hostAddr, @RequestHeader String Host) {
System. out .println(hostAddr + "-----" + Host );
return "requestHeader" ;
}7. 使用 @SessionAttributes 获取 HttpSession 信息