Springboot 2.x 請求參數之 @CookieValue 使用


一、@CookieValue 作用

使用該注解可以獲取指定名稱的 Cookie ,如果你想獲取更多的 Cookie 信息,可以使用 javax.servlet.http.Cookie 來定義形參類型

 

二、@CookieValue 注解聲明

// @CookieValue 獲取指定的 HTTP cookie
/**
 * Annotation which indicates that a method parameter should be bound to an HTTP cookie.
 *
 /*
 // 也可以將形式參數的類型設置為 javax.servlet.http.Cookie 類型,然后調用相應的方法來獲取 Cookie 信息
 /**
 * <p>The method parameter may be declared as type {@link javax.servlet.http.Cookie}
 * or as cookie value type (String, int, etc.).
 *
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 3.0
 * @see RequestMapping
 * @see RequestParame
 * @see RequestHeader
 * @see org.springframework.web.bind.annotation.RequestMapping
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CookieValue {

	// name 和 value 互為別名
	/**	
	 * Alias for {@link #name}.
	 */
	@AliasFor("name")
	String value() default "";

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

	// required 默認值為 true ,如果缺少指定名稱的 cookie ,則會報錯
	// 將 required 的值設置為 false ,即使 缺少指定名稱的 cookie ,也不會報錯
	/**
	 * Whether the cookie is required.
	 * <p>Defaults to {@code true}, leading to an exception being thrown
	 * if the cookie is missing in the request. Switch this to
	 * {@code false} if you prefer a {@code null} value if the cookie is
	 * not present in the request.
	 * <p>Alternatively, provide a {@link #defaultValue}, which implicitly
	 * sets this flag to {@code false}.
	 */
	boolean required() default true;

	// required 的值為 true 時,當缺少指定名稱的 cookie ,為了不報錯,可以使用 defaultValue 給這個 cookie 設置默認值
	/**
	 * The default value to use as a fallback.
	 * <p>Supplying a default value implicitly sets {@link #required} to
	 * {@code false}.
	 */
	String defaultValue() default ValueConstants.DEFAULT_NONE;
}

  

三、@CookieValue 使用

@RestController
public class RequestParamsController {

    @GetMapping("/cookieParams")
    public Map userInfo(
            // 根據指定的 cookie 的 name 獲取 value
            @CookieValue("Cookie_001") String cookie001,
            // 形參聲明為 javax.servlet.http.Cookie ,會將 cookie 的 value 該類中
            @CookieValue("Cookie_002") Cookie cookie){

        // 獲取 Cookie_002 的 name 和 value
        String name = cookie.getName();
        String value = cookie.getValue();

        Map map = new HashMap<String, Object>();
        map.put("Cookie_001",cookie001);
        map.put("name",name);
        map.put("value",value);

        return map;
    }
}

  

四、測試結果

4.1、請求攜帶的 Cookie 信息

4.2、響應信息

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM