Spring Boot session与cookie的使用


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;
	}
}
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";
	}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM