SpringBoot - Request域,Session域,Application域,Cookie域 获取与添加数据
1.向Request域添加与获取数据的方式 SpringMvc - @ModelAttribute注解
方式1 HttpServletRequest 添加与获取数据
@RequestMapping(value="meta") public void meta(HttpServletRequest request){ //添加数据 request.setAttribute("user",new Object()); //获取数据 Object user = request.getAttribute("username"); }
方式2 Model 添加与获取数据
@RequestMapping(value="meta") public void meta(Model model){ //添加数据 model.addAttribute("user", new Object()); //获取数据 Object user = model.getAttribute("user"); }
方式3 ModelMap 添加与获取数据
@RequestMapping(value="meta") public void meta(ModelMap modelMap){ //添加数据 modelMap.addAttribute("user",new Object()); //获取数据 Object user = modelMap.getAttribute("user"); }
方式4 @RequestAttribute注解
@RequestMapping(value="/arrtibuteTest") public void arrtibuteTest(@RequestAttribute(value="username") String username){ ... }
2.向Session域 添加与获取数据的方式
方式1 HttpSession 添加与获取数据
@RequestMapping(value="meta") public void meta(HttpSession httpSession){ //添加数据 httpSession.setAttribute("user",new Object()); //获取数据 Object user = httpSession.getAttribute("user"); }
方式2 HttpServletSession 添加与获取数据
@RequestMapping(value="meta") public void meta(HttpServletRequest request){ HttpSession session = request.getSession(); //添加数据 session.setAttribute("user",new Object()); //获取数据 Object user = session.getAttribute("user"); }
3.向Application 添加与获取数据
@RequestMapping(value="meta") public void meta(HttpSession httpSession){ ServletContext servletContext = httpSession.getServletContext(); //添加数据 servletContext.setAttribute("user",new Object()); //获取数据 Object user = servletContext.getAttribute("user"); }
4.添加Cookie与获取Cookie
@RequestMapping(value="meta") public void meta(@CookieValue("userSessionId")String userSessionId,HttpServletRequest request,HttpServletResponse response){ //添加Cookie Cookie cookie = new Cookie("userSessionId","JSESSIONID"); response.addCookie(cookie); //根据name 获取一个Cookie System.out.println(userSessionId); //获取所有Cookie Cookie[] cookies = request.getCookies(); }
posted on 2022-12-30 18:42 Mikasa-Ackerman 阅读(475) 评论(0) 编辑 收藏 举报