SpringBoot 控制和使用前端 Cookie

一、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

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章