本文介绍了spring mvc中使用@RequestMapping时,支持常用方法参数类型和返回类型。
常用的方法参数类型有:
- 1 PathVariable
- 2 RequestParam
- 3 RequestBody
- 4 HttpEntity
- 5 CookieValue
- 6 RequestHeader
- 7 自动封装form表单请求到对象中
- 8 HttpServletRequest HttpServletResponse
- 9 RequestMapping 参数配置params headers
常用的返回类型有:
代码工程名称:mvc
测试PO类
ModelAttributeVO
public class ModelAttributeVO { private String name; private String value; private Date date; // set/get方法略 }
public class VO { private String name; private String value; private Date date; // set/get方法略 }
以下代码都在RequestParameterController类中
@Controller: 表示此类对外提供url服务
@RequestMapping:此注解不仅可以作用在方法上,也可以作用在类上。如果作用在类上,则表示此值是类中的所有@RequestMapping方法的URL的前缀
@Controller @RequestMapping(value = "/request") // 全局URL public class RequestParameterController { .... }
下面用到jsp的页面如下,都在META-INF/resources/WEB-INF/page/reqparameter目录下:
showInput.jsp打印内容
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Request Parameter</title> </head> <body> ${map} </body> </html>
formModel.jsp测试form表单
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form name="myform" method="post" action="formModel"> <table> <tr> <td>First Name:</td> <td><input type="text" name="name" value="fisr name" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" name="value" value="lastName" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Save Changes" /> </td> </tr> </table> </form> </body> </html>
httpEntityForm.jsp测试form表单
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form name="myform" method="post" action="httpEntity"> <table> <tr> <td>First Name:</td> <td><input type="text" value="name" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" value="lastName" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Save Changes" /> </td> </tr> </table> </form> </body> </html>
作用:可以注入URL中的变量值,可以注入一个或者多个
单个 @PathVariable值代码:
@RequestMapping(value="/path/{ownerId}") public String pathVariable(@PathVariable String ownerId, Model model){ Map<String,Object> map = new HashMap<String,Object>(); map.put("ownerId", ownerId); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/path/1返回结果:
{ownerId=1}
作用: 可以注入URL中的变量值,可以注入一个或者多个
代码:
@RequestMapping(value="/path/{ownerId}/pet/{petId}") public String pathVariable2(@PathVariable String ownerId, @PathVariable String petId, Model model){ Map<String,Object> map = new HashMap<String,Object>(); map.put("ownerId", ownerId); map.put("petId", petId); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/path/1/pet/1234返回结果:
{petId=1234, ownerId=1}
作用:可以从请求参数中获取参数值
代码:
@RequestMapping(value="/requestParam", method = RequestMethod.GET) public String requestParam(@RequestParam("ownerId") int ownerId, ModelMap model) { Map<String,Object> map = new HashMap<String,Object>(); map.put("ownerId", ownerId); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/requestParam?ownerId=223返回结果:
{ownerId=223}
作用: 可以从请求参数中获取多个参数值
代码:
@RequestMapping(value="/requestParam2", method = RequestMethod.GET) public String requestParam2(@RequestParam Map<String,Object> map, ModelMap model) { // Map<String,Object> map = new HashMap<String,Object>(); // map.put("ownerId", ownerId); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/requestParam2?ownerId=223&a=4&c=5返回结果:
{ownerId=223, a=4, c=5}
作用:设置@RequestParam自定义参数:如设置默认值(defaultValue),是否必须(required)等等
代码:
@RequestMapping("/requestParam3") public String requestParam3(@RequestParam(value="inputStr", required=true, defaultValue="noInput") String inputStr, ModelMap model) { Map<String,Object> map = new HashMap<String,Object>(); map.put("inputStr",inputStr ); model.addAttribute("map",map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/requestParam3?inputStr=myInput 此URL有inputStr值,则其值为myInput值
{inputStr=myInput}
访问URL:
http://127.0.0.1:8080/request/requestParam3此URL没有inputStr值,则其值为默认值,即noInput
返回结果:
{inputStr=noInput}
作用:@RequestBody: 获取请求的内容。请求内容为JSON,因为本工程设置请求为json,所以demo为:{“a”:1}
代码:
@RequestMapping(value = "/requestBody", method = RequestMethod.POST) public String requestBody(@RequestBody String body, ModelMap model){ Map<String,Object> map = new HashMap<String,Object>(); map.put("body",body ); model.addAttribute("map",map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/requestBody内容为{“a”:1}
此请求为POST,需要使用postman等模拟POST请求
返回结果:
{body={"a":1}}
作用:HttpEntity,可以操作更原始的请求方法
代码:
@RequestMapping(value="/httpEntity", method = RequestMethod.GET) public String httpEntity(ModelMap model){ return "reqparameter/httpEntityForm"; } @RequestMapping("/httpEntity") public String httpEntity2(HttpEntity<byte[]> requestEntity, ModelMap model){ // 获取header String acceptLanguage = requestEntity.getHeaders().getFirst("Accept-Language"); // 获取内容:获取body的内容为空,暂时不知道原因 byte[] requestBody = requestEntity.getBody(); Map<String,Object> map = new HashMap<String,Object>(); map.put("acceptLanguage", acceptLanguage); // map.put("content", new String(requestBody)); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/httpEntity返回结果:
输入上面URL,进入form表单,填写内容后,会转到新的页面如下
{acceptLanguage=zh-CN,zh;q=0.9,zh-TW;q=0.8}
作用:获取cookie里的值
代码:
@RequestMapping("/cookieValue") public String cookieValue(@CookieValue("JSESSIONID") String cookie,ModelMap model) { Map<String,Object> map = new HashMap<String,Object>(); map.put("cookie", cookie); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/cookieValue返回结果:
{cookie=38EDB55B71BB4CCA6EF1A2CDA7F1BCC0}
作用:操作http header的值
获取指定header里的值代码:
@RequestMapping("/requestHeader") public String requestHeader ( @RequestHeader ("User-Agent") String userAgent, @RequestHeader ("Host") String host, @RequestHeader ("Cache-Control") String cacheControl, ModelMap model) { Map<String,Object> map = new HashMap<String,Object>(); map.put("User-Agent", userAgent); map.put("Host", host); map.put("Cache-Control", cacheControl); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/requestHeader 此请求刷新需求刷新多次
返回结果:
{Cache-Control=max-age=0, User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36, Host=127.0.0.1:8080}
代码:
@RequestMapping("/requestHeaderMap") public String requestHeaderMap (@RequestHeader Map<String,String> map, ModelMap model) { model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/requestHeaderMap返回结果:
{host=127.0.0.1:8080, connection=keep-alive, user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36, upgrade-insecure-requests=1, accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8, accept-encoding=gzip, deflate, br, accept-language=zh-CN,zh;q=0.9,zh-TW;q=0.8, cookie=JSESSIONID=38EDB55B71BB4CCA6EF1A2CDA7F1BCC0}
作用:
代码:
@RequestMapping(value="/formModel", method = RequestMethod.GET) public String form(){ return "reqparameter/formModel"; } @RequestMapping("/formModel") public String formPost(VO vo, ModelMap model){ Map<String,Object> map = new HashMap<String,Object>(); map.put("name", vo.getName()); map.put("value", vo.getValue()); map.put("date", vo.getDate()); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/request/formModel 此URL进入form表单,我们填写内容后,会提交到formPost方法,此时时会自动封装值到VO对象中,打印内容如下
返回结果:
{date=Sun Nov 12 22:11:22 CST 2017, name=fisr name, value=lastName}
作用:直接操作原始的HttpServletRequest 和 HttpServletResponse
代码:
@RequestMapping("/httpServlet") public void formPost(HttpServletRequest request, HttpServletResponse response) throws IOException{ String userAgent = request.getHeader("User-Agent"); String host = request.getHeader("Host"); String cacheControl = request.getHeader("Cache-Control"); PrintWriter pw = response.getWriter(); pw.println("User-Agent :"+ userAgent); pw.println("Host :" + host); pw.println("Cache-Control :" + cacheControl); }
访问URL:
http://127.0.0.1:8080/request/httpServlet返回结果:
User-Agent :Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36 Host :127.0.0.1:8080 Cache-Control :null
作用:通过params过滤请求,如下面的代码,只有URL带上myParam=myValue才能进入
代码:
@RequestMapping(value="/reqparameters/{ownerId}", method = RequestMethod.GET, params="myParam=myValue") public String reqParameters(@PathVariable String ownerId, Model model){ Map<String,Object> map = new HashMap<String,Object>(); map.put("ownerId", ownerId); model.addAttribute("map", map); return "reqparameter/showInput"; t"; }
访问URL: http://127.0.0.1:8080/request/reqparameters/1?myParam=myValue 可以进入到这个方法,
但是以下URL无法进入这个方法: http://127.0.0.1:8080/request/reqparameters/1
备注: 其他条件,也可以这样: “myParam”, “!myParam”, or “myParam=myValue”
作用:通过headers过滤请求,请求头里必须带上myParam,且值为myValue
代码:
@RequestMapping(value="/reqparameters/{ownerId}", method = RequestMethod.GET, headers="myParam=myValue") public String headerParameters(@PathVariable String ownerId, Model model){ Map<String,Object> map = new HashMap<String,Object>(); map.put("ownerId", ownerId); model.addAttribute("map", map); return "reqparameter/showInput"; }
访问URL:
http://127.0.0.1:8080/reqparameters/1 如果使用POST请求,请使用postman,并在请求头里必须带上myParam,且值为myValue
以下代码都在此类中
@Controller @RequestMapping(value = "/response") public class ResponseParameterController { ... }
下面用到jsp的页面如下,都在META-INF/resources/WEB-INF/page/resparameter目录下:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Request Parameter</title> </head> <body> ${map} </body> </html>
默认情况下,返回一个字符串,表示转到一个指定页面,上面的demo都是这个模式
@RequestMapping(value="/path/{ownerId}") public String pathVariable(@PathVariable String ownerId, Model model){ Map<String,Object> map = new HashMap<String,Object>(); map.put("ownerId", ownerId); model.addAttribute("map", map); return "reqparameter/showInput"; }
作用:此注解注解的方法返回字符串
代码:
@RequestMapping(value = "/responseBody", method = RequestMethod.GET) @ResponseBody public String responseBodyString() { return "Hello World"; }
访问URL:
http://127.0.0.1:8080/response/responseBody返回结果:
"Hello World"
作用:方法返回对象,返回客户端时系统自动转化为json
代码:
@RequestMapping(value = "/responseBodyMode", method = RequestMethod.GET) @ResponseBody public VO responseBodyMode() { return new VO(); }
访问URL:
http://127.0.0.1:8080/response/responseBodyMode返回结果:
{ "date":1510497345620, "name":"name", "value":"value" }
作用:返回一个ResponseEntity
代码:
@RequestMapping("/responseEntity") public ResponseEntity<String> responseEntity(){ // do something with request header and body HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED); }
访问URL:
http://127.0.0.1:8080/response/responseEntity返回结果:
"Hello World"
作用:返回ModelAndView
代码:
public ModelAndView modelAndView(){ Map<String,Object> map = new HashMap<String,Object>(); map.put("ownerId", "1"); map.put("petId", "23"); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("resparameter/showInput"); modelAndView.addObject("map", map); return modelAndView; }
访问URL:
http://127.0.0.1:8080/response/modelAndView返回结果:
{petId=23, ownerId=1}
上文的详细代码 见github代码,请尽量使用tag v0.4,不要使用master,因为master一直在变,不能保证文章中代码和github上的代码一直相同