zoukankan      html  css  js  c++  java
  • 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";
    	}
    }
    
  • 相关阅读:
    cas 单点登录(SSO)实验之二: cas-client
    前端要给力之:语句在JavaScript中的值
    【Linux】Tomcat安装及一个服务器配置多个Tomcat
    【Linux】 JDK安装及配置 (tar.gz版)
    Android自动化测试中AccessibilityService获取控件信息(1)
    Android自动化框架 模拟操作 模拟测试
    Android应用程序如何调用shell脚本(一)
    关于lidroid xUtils 开源项目
    android 开源项目列表【持续整理中。。。】
    android开发常用组件【持续更新中。。。】
  • 原文地址:https://www.cnblogs.com/dowhile/p/Spring-Boot-session-yucookie-de-shi-yong.html
Copyright © 2011-2022 走看看