Spring WebFlux中Cookie的读写

全文共 705 个字

WebFLux与WebMvc的差异

WebFlux读写Cookie不像WebMvc那么直接,最主要的原因是WebMvc是基于Servlet规范的,而WebFlux仅仅遵守的是HTTP协议。所以在使用的时候会发现HttpServletRequestHttpServletResponse这些Servlet层级的接口根本就无法使用。

CookieServlet并没有太直接的关系,前者是属于HTTP规范的而后者是一个J2EE的规范,在应用层面仅有的联系就是Servlet会读写Cookie中的JSESSIONID来标记与前端浏览器和服务端的关系。而HttpServletRequestHttpServletResponse仅是Servlet为请求和响应提供headerbody管理的接口。

WebFlux的Cookie管理

WebFlux目前并没有为写Cookie提供任何工具。这就需要开发者按照HTTP的规范来写Cookie。 在HTTP协议交互的过程中,服务端可以通过在response中添加Set-Cookie头来让浏览器记录Cookie,而浏览器则在request中使用Cookie头来传递cookie。

写Cookie

cookie使用ResponseEntity向response头中添加Set-Cookie即可。CookieBuilder的代码比较长,它是用于构建一个cookie字符串,Set-Cookie头除了设置key=value,还可以设置过期日期expires,域名domain,路径path等。

@RestController
@RequestMapping("/cookie")
public class CookieReadAWriteController {
	@GetMapping("/write")
	public ResponseEntity<String> cookieWrite() {
		HttpHeaders headers = new HttpHeaders();
		String cookie = new CookieBuilder().setKey("cookie-text")
			.setValue(cookieText)
			.setMaxAge(840000)
			.setPath("/")
			.build();
		headers.add("Set-Cookie", cookie);
		return new ResponseEntity<String>("hi," + userName, headers, HttpStatus.OK);
	}
}


class CookieBuilder {
	private String key;
	private String value;
	private String expires;
	private String domain;
	private String path;

	public CookieBuilder setKey(String key) {
		this.key = key;
		return this;
	}

	public CookieBuilder setValue(String value) {
		this.value = value;
		return this;
	}

	public CookieBuilder setMaxAge(long ms) {
		//cookie的过期日期为GMT格式的时间。
		Date date = new Date(new Date().getTime() + ms);
		SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		this.expires = sdf.format(date);
		return this;
	}

	public CookieBuilder setDomain(String domain) {
		this.domain = domain;
		return this;
	}

	public CookieBuilder setPath(String path) {
		this.path = path;
		return this;
	}

	public String build() {
		StringBuilder sb = new StringBuilder();
		sb.append(this.key);
		sb.append("=");
		sb.append(this.value);
		sb.append(";");
		if (null != this.expires) {
			sb.append("expires=");
			sb.append(this.expires);
			sb.append(";");
		}
		if (null != this.domain) {
			sb.append("domain=");
			sb.append(this.domain);
			sb.append(";");
		}
		if (null != this.path) {
			sb.append("path=");
			sb.append(this.path);
			sb.append(";");
		}
		return sb.toString();
	}
}

读cookie

获取cookie就比较直观,可以直接使用@CookieValue这个Annotation来获取:

@RestController
@RequestMapping("/cookie")
public class CookieReadAWriteController {
	@GetMapping("/read/annotation")
	/**
	 * @param value
	 * @return
	 */
	public String cookieReadAnnotation(@CookieValue("cookie-text") String value) {
		return "当前Cookie中的内容" + value;
	}
}

也可以直接从Request的Header中获取:

@RestController
@RequestMapping("/cookie")
public class CookieReadAWriteController {
	@GetMapping("/read/annotation")
	/**
	 * @param value
	 * @return
	 */
	@GetMapping("/read/entity")
	public String cookieReadEntity(RequestEntity<String> entity) {
		HttpHeaders headers = entity.getHeaders();
		List<String> cookie = headers.get("Cookie");
		return "当前Cookie中的内容" + cookie;
	}
}

使用Annotatin是直接标记Cookiekey来获取value。而使用RequestEntity需要从头中先获取Cookie的内容,然后再解析keyvalue,存在一个key对应多个value的情况需要使用RequestEntity