• 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";
    	}
    }
    
  • 相关阅读:
    NYOJ 32(组合数)
    NYOJ 289(01背包)
    批量修改文件(图片)名称
    解决IIS7虚拟目录出现HTTP 错误 500.19(由于权限不足而无法读取配置文件)的问题
    MPP(最下正周期)
    wcf学习网站
    winform中用户输入查询与拼音首字母的结合,提高用户的操作体验 (转)
    通过SvcUtil.exe生成客户端代码和配置(转)
    WinMail 搭建邮件服务器。
    quick easy ftp server软件在机子上架设了个服务器
  • 原文地址:https://www.cnblogs.com/dowhile/p/Spring-Boot-session-yucookie-de-shi-yong.html
Copyright © 2020-2023  润新知