在Spring Controller中将数据缓存到session

Servlet方案

在Controller的方法的参数列表中,添加一个javax.servlet.http.HttpSession类型的形参。spring mvc会 自动把当前session对象注入这个参数,此后可以使用setAttribute(String key, Object value)将数据缓存到session,使用removeAttribute( String key)将指定的数据从session缓存中移除。

 1 package cn.sinobest.jzpt.demo.login.web;
 2 import javax.servlet.http.HttpSession;
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.ui.Model;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 /**
 7  * 登陆相关Controller.<br>
 8  * H - HttpSession.
 9  * @author lijinlong
10  *
11  */
12 @Controller
13 @RequestMapping("demo/h_login")
14 public class HLoginController {
15      
16     @RequestMapping("/login")
17     public String login(Model model, String username, HttpSession session) {
18         Logger.logger.debug("in HLoginController.login...");
19         String currUsername = session.getAttribute("username") == null ? null
20                 : session.getAttribute("username").toString();
21             // 尝试从session中获取username数据。
22          
23         boolean usernameIsNull = username == null || username.isEmpty();
24         boolean currunIsNull = currUsername == null || currUsername.isEmpty();
25         if (usernameIsNull && currunIsNull) {
26             return View.VIEW_LOGIN;
27         }
28          
29         if (!usernameIsNull) {
30             session.setAttribute("username", username);
31                 // 将username缓存到session中。
32         }
33         return View.VIEW_LOGOUT;
34     }
35      
36     /**
37      * 注销.
38      * @param model
39      * @param session
40      * @return
41      */
42     @RequestMapping("/logout")
43     public String logout(Model model, HttpSession session) {
44         Logger.logger.debug("in HLoginController.logout...");
45         session.removeAttribute("username");
46             // 将username从session中移除。
47         return View.VIEW_LOGIN;
48     }
49 }
LoginController.java

Spring方案

spring mvc提供了内嵌的支持方案:

  1. 将数据缓存到session
    对Controller使用org.springframework.web.bind.annotation.SessionAttributes注解,可以将指定名称 或者 类型的数据,在model.addAttribute( String key,  Object value)时,缓存到session中。
  2. 清除session中的数据
    调用org.springframework.web.bind.support.SessionStatus实例的setComplete(),在方法的参数列表中声明SessionStatus类型的参数,会被自动注入。
 1 package cn.sinobest.jzpt.demo.login.web;
 2 import org.springframework.stereotype.Controller;
 3 import org.springframework.ui.Model;
 4 import org.springframework.web.bind.annotation.ModelAttribute;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.SessionAttributes;
 7 import org.springframework.web.bind.support.SessionStatus;
 8 /**
 9  * 登陆相关Controller.<br>
10  * S - Spring Session.
11  * @author lijinlong
12  *
13  */
14 @Controller
15 @RequestMapping("demo/s_login")
16 @SessionAttributes("username") // 指定了key为username的数据,会被放入session中。
17 public class SLoginController {
18     @RequestMapping("/login")
19     public String login(Model model, String username) {
20         Logger.logger.debug("in SLoginController.login...");
21         String currUsername = model.asMap().get("username") == null ? null
22                 : model.asMap().get("username").toString();
23             // 尝试从session中获取username(spring mvc会自动把session中的数据装载到model中)。
24          
25         boolean usernameIsNull = username == null || username.isEmpty();
26         boolean currunIsNull = currUsername == null || currUsername.isEmpty();
27         if (usernameIsNull && currunIsNull) {
28             return View.VIEW_LOGIN;
29         }
30          
31         if (!usernameIsNull) {
32             model.addAttribute("username", username);
33                 // username会被放入session中(key和@SessionAttributes的参数匹配)。
34         }
35         return View.VIEW_LOGOUT;
36     }
37      
38     @RequestMapping("/logout")
39     public String logout(SessionStatus status,
40             @ModelAttribute("username") String currUsername) {
41         Logger.logger.debug("in SLoginController.logout...");
42         Logger.logger.debug("current user is:" + currUsername);
43         status.setComplete();
44             // 清除session中的attribute
45         return View.VIEW_LOGIN;
46     }
47 }
LoginController

SessionAttributes的使用方法

  • 匹配单一的key
     @SessionAttributes("username") // 匹配key=username的数据 
  • 匹配key数组
     @SessionAttributes({"username", "password"}) // 匹配key=username或者password的数据 
  • 匹配单一类
     @SessionAttributes(types=String.class) // 匹配String类型的数据 

  • 匹配类数组
     @SessionAttributes(types={String.class, List.class}) // 匹配String类型或List类型的数据 
  • 混合匹配
     @SessionAttributes(value={"username", "password"}, types={String.class, List.class}) 

ModelAttribute

使用ModelAttribute,可以自动将session中指定的参数注入到方法的形参;但是如果session中没有指定的参数,会抛出异常:
org.springframework.web.HttpSessionRequiredException: Session attribute 'username' required - not found in session

Model中的数据

Spring 会把Session中的数据装载到Model中,所以使用model.asMap().get("username")可以获取 session中的数据。返回页面前,spring会把Model中的数据放入requestScope,所以在页面可以使 用${requestScope.username}来获取数据。

原文地址:https://www.cnblogs.com/ywjy/p/5016034.html