SpringBoot 控制和使用前端 Cookie

送分小仙女□ 提交于 2020-02-26 14:02:50

一、Java 代码

package com.swmfizl.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody
@CrossOrigin(value = "http://localhost", maxAge = 3600, allowCredentials = "true")
public class CookieController {
	@RequestMapping(value = "setCookie", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public Map<String, Object> setCookie(HttpServletResponse response) {
		Map<String, Object> res = new HashMap<String, Object>();
		Cookie cookie = new Cookie("token", "cdb85c2f-2695-4982-a3e8-95754f8b50e0");
		cookie.setPath("/");
		cookie.setMaxAge(3600);
		response.addCookie(cookie);
		res.put("cookie", cookie );
		res.put("code", 0);
		res.put("msg", "添加cookie成功");
		return res;
	}

	@RequestMapping(value = "getCookie", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public Map<String, Object> getCookie(HttpServletRequest request) {
		Map<String, Object> res = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		res.put("cookies", cookies);
		res.put("code", 0);
		res.put("msg", "获取cookies成功");
		return res;
	}
}

二、前端代码(Vue)

new Vue({
	el: "#App",
	data: {

	},
	methods: {
		/**
		 * 设置Cookie
		 * @param {Funtion} callFunction 回调方法
		 */
		setCookie: function(callFunction) {
			axios({
				method: 'post',
				url: "http://localhost:8080/setCookie",
				withCredentials: true,
			}).then(function(res) {
				callFunction(res)
			});
		},

		/**
		 * 获取Cookie
		 * @param {Funtion} callFunction 回调方法
		 */
		getCookie: function(callFunction) {
			axios({
				method: 'post',
				url: "http://localhost:8080/getCookie",
				withCredentials: true,
			}).then(function(res) {
				callFunction(res)
			});
		}
	},
	mounted: function() {
		var THIS = this;
		// 测试Cookie 使用
		this.setCookie(function(res) {
			console.log(res);
			THIS.getCookie(function(res) {
				console.log(res)
			})
		})
	}
})

三、运行前端页面,成功设置和获取 Cookie

在这里插入图片描述
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!