欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Spring boot】session与cookie的使用

程序员文章站 2024-03-19 22:41:10
...

总体而言使用方法非常简单,可以直接参考下面的例子。

package cn.smileyan.boot.test.session;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
@CrossOrigin
public class HelloSessionController {
	
	@RequestMapping("/add")
	public String addSession(HttpServletRequest httpServletRequest,
							@RequestParam("username")String username) {
		HttpSession session = httpServletRequest.getSession();
		session.setAttribute("username",username);
		session.setMaxInactiveInterval(10000);
		return "添加成功";
	}
	
	@RequestMapping("/show")
	public Object showSession(HttpServletRequest httpServletRequest) {
		HttpSession session = httpServletRequest.getSession();
		Object object = session.getAttribute("username");
		return object;
	}
	
}

测试方法:打开浏览器,访问addSession方法对应的访问路径,然后添加url参数,比如说

localhost/test/add?username=smileyan

然后直接访问这个路径,可以看到“添加成功”这个返回结果。

 

 

道理基本相同,cookie的使用也是如此

package cn.smileyan.boot.test.session;

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

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cookie")
public class HelloCookieController {
	@RequestMapping("/add")
	public String addCookie(HttpServletRequest request,HttpServletResponse response,
					@RequestParam("username")String username) {
		Cookie cookie = new Cookie("username", username);
		cookie.setPath(request.getContextPath());
		cookie.setMaxAge(80000);
		response.addCookie(cookie);
		return "添加成功";
	}
	
	@RequestMapping("/show")
	public String showCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("username")) {
				System.out.println(cookie.getName());
				System.out.println(cookie.getValue());
				return cookie.getValue().toString();
			}
		}
		return "null";
	}
}

补充:

如果setSession和getSession所在的类不同的话,需要修改path为"/"。