专栏名称: hryou0922
目录
相关文章推荐
新周刊  ·  为什么高铁一到山东,速度就变慢 ·  10 小时前  
三联生活周刊  ·  爱听芭乐歌,活该被鄙视吗? ·  昨天  
51好读  ›  专栏  ›  hryou0922

Spring Boot系列九 spring mvc的@RequestMapping支持的方法参数类型和返回类型

hryou0922  · 掘金  ·  · 2018-01-31 02:02

正文

1. 概述

本文介绍了spring mvc中使用@RequestMapping时,支持常用方法参数类型和返回类型。

常用的方法参数类型有:
- 1 PathVariable
- 2 RequestParam
- 3 RequestBody
- 4 HttpEntity
- 5 CookieValue
- 6 RequestHeader
- 7 自动封装form表单请求到对象中
- 8 HttpServletRequest HttpServletResponse
- 9 RequestMapping 参数配置params headers

常用的返回类型有:

  • 1 返回一个页面的地址
  • 2 ResponseBody
  • 3 ResponseEntity
  • 4 ModelAndView

2. 前提条件

代码工程名称:mvc

测试PO类
ModelAttributeVO

public class ModelAttributeVO {
    private String name;
    private String value;
    private Date date;
    // set/get方法略
}

VO

public class VO {
    private String name;
    private String value;
    private Date date;
    // set/get方法略
}

3. @RequestMapping支持的方法参数类型

3.1. RequestParameterController

以下代码都在RequestParameterController类中

@Controller: 表示此类对外提供url服务 @RequestMapping:此注解不仅可以作用在方法上,也可以作用在类上。如果作用在类上,则表示此值是类中的所有@RequestMapping方法的URL的前缀

@Controller
@RequestMapping(value = "/request") // 全局URL
public class RequestParameterController {
    ....
}

3.2. 使用的jsp

下面用到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>

3.3. @PathVariable

作用:可以注入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}

多个 @PathVariable值
作用: 可以注入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}

3.4. @RequestParam

通过@RequestParam注入单个值
作用:可以从请求参数中获取参数值
代码:

@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}

通过@RequestParam注入多个值
作用: 可以从请求参数中获取多个参数值
代码:

    @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: required、defaultValue
作用:设置@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}

3.5. @RequestBody

作用:@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}}

3.6. HttpEntity

作用: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}

3.7. @CookieValue

作用:获取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







请到「今天看啥」查看全文