注解之@CookieValue

@RequestHeader以及@CookieValue这两个注解用法相似,属性也相同,因此,写在一块儿。两者属性和RequestParam的属性同样,用法也几乎同样。html

做用

@RequestHeader注解主要是将请求头的信息区数据,映射到功能处理方法的参数上。@CookieValue注解主要是将请求的Cookie数据,映射到功能处理方法的参数上。cookie

属性说明

Annotation which indicates that a method parameter should be bound to an HTTP cookie.app

它将一个HTTP cookie绑定于方法的一个参数。post

一、value:绑定的参数名称,String类型。ui

二、required:是否必须包含value,boolean类型,默认为 true,表示请求参数中必须包含对应的参数;若不存在,将抛出异常。spa

三、defaultValue:默认值,String类型。当没有传参时将使用此值赋值。调试

案例分析

两者在开发中不多被用到,了解便可。下面的代码示例演示了如何获取cookie JSESSIONID,Accept和User-agent 的值:code

@RestController

@RequestMapping("/user")

public class UserController {  

    @RequestMapping("/displayHeaderInfo")

    public Map<String, Object> displayHeaderInfo(@RequestHeader("User-agent") String userAgent, @RequestHeader(value = "Accept") String[] accepts,

            @CookieValue("JSESSIONID") String cookie) {

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

        response.put("accepts", accepts);

        response.put("userAgent", userAgent);

        response.put("cookie", cookie);

        return response;

    }

}

postman调试结果以下:htm

 

转载于:https://www.cnblogs.com/east7/p/10303180.htmlblog

@RequestHeader以及@CookieValue这两个注解用法相似,属性也相同,因此,写在一块儿。两者属性和RequestParam的属性同样,用法也几乎同样。

做用

@RequestHeader注解主要是将请求头的信息区数据,映射到功能处理方法的参数上。@CookieValue注解主要是将请求的Cookie数据,映射到功能处理方法的参数上。

属性说明

Annotation which indicates that a method parameter should be bound to an HTTP cookie.

它将一个HTTP cookie绑定于方法的一个参数。

一、value:绑定的参数名称,String类型。

二、required:是否必须包含value,boolean类型,默认为 true,表示请求参数中必须包含对应的参数;若不存在,将抛出异常。

三、defaultValue:默认值,String类型。当没有传参时将使用此值赋值。

案例分析

两者在开发中不多被用到,了解便可。下面的代码示例演示了如何获取cookie JSESSIONID,Accept和User-agent 的值:

@RestController

@RequestMapping("/user")

public class UserController {  

    @RequestMapping("/displayHeaderInfo")

    public Map<String, Object> displayHeaderInfo(@RequestHeader("User-agent") String userAgent, @RequestHeader(value = "Accept") String[] accepts,

            @CookieValue("JSESSIONID") String cookie) {

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

        response.put("accepts", accepts);

        response.put("userAgent", userAgent);

        response.put("cookie", cookie);

        return response;

    }

}

postman调试结果以下:

相关文章
相关标签/搜索