29、请求处理-常用参数注解使用

注解:

  • @PathVariable 路径变量

  • @RequestHeader 获取请求头

  • @RequestParam 获取请求参数(指问号后的参数,url?a=1&b=2)

  • @CookieValue 获取Cookie值

  1. @PathVariable 路径变量

一、注解解释

@PathVariable 映射 URL 绑定的占位符

通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx”) 绑定到操作方法的入参中。

一般与@RequestMapping(method = RequestMethod.GET)一起使用

@RequestMapping("/getUserById/{name}")
    public User getUser(@PathVariable("name") String name){
        return userService.selectUser(name);
    }
1、若方法参数名称和需要绑定的url中变量名称一致时,可以简写:
@RequestMapping("/getUser/{name}")
    public User getUser(@PathVariable String name){
        return userService.selectUser(name);
    }
2、若方法参数名称和需要绑定的url中变量名称不一致时,写成:
@RequestMapping("/getUserById/{name}")
    public User getUser(@PathVariable("name") String userName){
        return userService.selectUser(userName);
    }
  1. @RequestHeader 获取请求头

当一个客户端(通常是浏览器)向Web服务器发送一个请求是,它要发送一个请求的命令行,一般是GET或POST命令,当发送POST命令时,它还必须向服务器发送一个叫“Content-Length”的请求头(Request Header) 用以指明请求数据的长度,除了Content-Length之外,它还可以向服务器发送其它一些Headers,如:

  • Accept 浏览器可接受的MIME类型

  • Accept-Charset 浏览器支持的字符编码

  • Accept-Encoding 浏览器知道如何解码的数据编码类型(如 gzip)。Servlets 可以预先检查浏览器是否支持gzip并可以对支持gzip的浏览器返回gzipped的HTML页面,并设置Content-Encoding回应头(response header)来指出发送的内容是已经gzipped的。在大多数情况下,这样做可以加快网页下载的速度。

  • Accept-Language 浏览器指定的语言,当Server支持多语种时起作用。

  • Authorization 认证信息,一般是对服务器发出的WWW-Authenticate头的回应。

  • Connection 是否使用持续连接。如果servlet发现这个字段的值是Keep-Alive,或者由发出请求的命令行发现浏览器支持 HTTP 1.1 (持续连接是它的默认选项),使用持续连接可以使保护很多小文件的页面的下载时间减少。

  • Content-Length (使用POST方法提交时,传递数据的字节数)

  • Cookie (很重要的一个Header,用来进行和Cookie有关的操作,详细的信息将在后面的教程中介绍)

  • Host (主机和端口)

  • If-Modified-Since (只返回比指定日期新的文档,如果没有,将会反回304 "Not Modified")

  • Referer (URL)

  • User-Agent (客户端的类型,一般用来区分不同的浏览器)

如果你想更多的了解Request Header的内容,你可以访问W3C的网站。

@RequestHeader是将请求头信息和控制器方法的形参创建映射关系

@RequestHeader注解一共有三个属性:

  • value(值)

  • required(是否为必须的,默认为true)

  • defaultValue(当没值的时候,采取此值)。

  1. @RequestParam 获取请求参数

  1. 作用

把请求中的指定名称的参数(即为请求链接中问号后的参数,url?a=1&b=2)传递赋值给控制器中的形参。通常用于GET请求。

@RequestParam用来处理Content-Type 为 application/x-www-form-undencoded编码的内容,Content-Type 默认为该属性。

@RequestParam也可用于其它类型的请求,例如:POST、DELETE等请求。

POST请求
由于@RequestParam是用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容的,所以在postman中,要选择body的类型为 x-www-form-urlencoded,这样在headers中就自动变为了 Content-Type : application/x-www-form-urlencoded 编码格式。
  1. 属性

1. value / name:请求参数中的名称 (必写参数)

2. required:请求参数中是否必须提供此参数,默认值是true,true为必须提供

3. defaultValue:默认值

关于是value / name属性,源码是这样写的

 /**
 * Annotation which indicates that a method parameter should be bound to a web
 * request parameter.
 *
 * <p>Supported for annotated handler methods in Spring MVC and Spring WebFlux
 * as follows:
 * <ul>
 * <li>In Spring MVC, "request parameters" map to query parameters, form data,
 * and parts in multipart requests. This is because the Servlet API combines
 * query parameters and form data into a single map called "parameters", and
 * that includes automatic parsing of the request body.
 * <li>In Spring WebFlux, "request parameters" map to query parameters only.
 * To work with all 3, query, form data, and multipart data, you can use data
 * binding to a command object annotated with {@link ModelAttribute}.
 * </ul>
 *
 * <p>If the method parameter type is {@link Map} and a request parameter name
 * is specified, then the request parameter value is converted to a {@link Map}
 * assuming an appropriate conversion strategy is available.
 *
 * <p>If the method parameter is {@link java.util.Map Map&lt;String, String&gt;} or
 * {@link org.springframework.util.MultiValueMap MultiValueMap&lt;String, String&gt;}
 * and a parameter name is not specified, then the map parameter is populated
 * with all request parameter names and values.
 *
 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 2.5
 * @see RequestMapping
 * @see RequestHeader
 * @see CookieValue
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {

    /**
     * Alias for {@link #name}.
     */
    @AliasFor("name")
    String value() default "";

    /**
     * The name of the request parameter to bind to.
     * @since 4.2
     */
    @AliasFor("value")
    String name() default "";

    /**
     * Whether the parameter is required.
     * <p>Defaults to {@code true}, leading to an exception being thrown
     * if the parameter is missing in the request. Switch this to
     * {@code false} if you prefer a {@code null} value if the parameter is
     * not present in the request.
     * <p>Alternatively, provide a {@link #defaultValue}, which implicitly
     * sets this flag to {@code false}.
     */
    boolean required() default true;

    /**
     * The default value to use as a fallback when the request parameter is
     * not provided or has an empty value.
     * <p>Supplying a default value implicitly sets {@link #required} to
     * {@code false}.
     */
    String defaultValue() default ValueConstants.DEFAULT_NONE;

}

源码注解的意思是name的别名是value,value的别名是name。所以功能相同,二者皆可。

  1. 使用

@RequestParam 注解的 value 属性值没有对应上请求链接中 name 值则会直接报400错误,因为 required 属性默认为 true ,如果加上 required=false ,没对应上则不会报错,而是获取值为 null

  1. 用例:
@RestController
public class ParameterTestController {


    //  car/2/owner/zhangsan
    @GetMapping("/car/{id}/owner/{username}")
    public Map<String,Object> getCar(@PathVariable("id") Integer id,
                                     @PathVariable("username") String name,
                                     @PathVariable Map<String,String> pv,
                                     @RequestHeader("User-Agent") String userAgent,
                                     @RequestHeader Map<String,String> header,
                                     @RequestParam("age") Integer age,
                                     @RequestParam("inters") List<String> inters,
                                     @RequestParam Map<String,String> params,
                                     @CookieValue("_ga") String _ga,
                                     @CookieValue("_ga") Cookie cookie){

        Map<String,Object> map = new HashMap<>();

//        map.put("id",id);
//        map.put("name",name);
//        map.put("pv",pv);
//        map.put("userAgent",userAgent);
//        map.put("headers",header);
        map.put("age",age);
        map.put("inters",inters);
        map.put("params",params);
        map.put("_ga",_ga);
        System.out.println(cookie.getName()+"===>"+cookie.getValue());
        return map;
    }


    @PostMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map<String,Object> map = new HashMap<>();
        map.put("content",content);
        return map;
    }
}
  1. @CookieValue 获取Cookie值

@CookieValue映射cookie值即,注解能将一个方法参数与一个HTTP cookie的值进行绑定,能够获取到Cookie中的值。

  1. @CookieValue参数

  1、value:参数名称

  2、required:是否必须

  3、defaultValue:默认值

  1. @CookieValue使用案例
/**
 * 验证用户信息
 * @param token
 * @return
 */
@GetMapping("verify") //直接获取cookie中的token值
public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN") String token) {
    try {
        // 获取token信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
        // 成功后直接返回
        return ResponseEntity.ok(userInfo);
    } catch (Exception e) {
        // 抛出异常,证明token无效,直接返回401
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
    }
}


引用链接:https://blog.csdn.net/weixin_45393094/article/details/108814901

引用链接:https://blog.csdn.net/qaz13177_58_/article/details/6597575

引用链接:https://blog.csdn.net/qq_44543508/article/details/101026720

引用链接:https://blog.csdn.net/sswqzx/article/details/85450711

引用链接:https://blog.csdn.net/weixin_46058921/article/details/127794325

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值