java - Spring 3.0 设置和获取 session 属性

标签 java spring session-variables

我想从 session 范围读取域对象 (UserVO)。

我在一个名为 WelcomeController 的 Controller 中设置 UserVO

@Controller
@RequestMapping("/welcome.htm")
public class WelcomeController {
@RequestMapping(method = RequestMethod.POST)
    public String processSubmit(BindingResult result, SessionStatus status,HttpSession session){
      User user = loginService.loginUser(loginCredentials);
     session.setAttribute("user", user);
         return "loginSuccess";
    }
}

我可以在 jsp 页面中使用该对象 <h1>${user.userDetails.firstName}</h1>

但我无法从另一个 Controller 读取值,

我正在尝试读取 session 属性如下:

@Controller
public class InspectionTypeController {
@RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
 public String addInspectionType(InspectionType inspectionType, HttpSession session)
 {
           User user = (User) session.getAttribute("user");
           System.out.println("User: "+ user.getUserDetails().getFirstName);

        }
} 

最佳答案

您显示的代码应该 工作 - HttpSession 在 Controller 之间共享,并且您使用相同的属性名称。因此,您没有向我们展示的其他问题。

但是,无论它是否有效,Spring 都提供了一种更优雅的方法来将模型对象保留在 session 中,使用 @SessionAttribute 注释(参见 docs)。

例如(我没有测试过这个,但它给了你想法):

@Controller
@RequestMapping("/welcome.htm")
@SessionAttributes({"user"})
public class WelcomeController {
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(ModelMap modelMap){
       User user = loginService.loginUser(loginCredentials);
       modelMap.addtAttribute(user);
       return "loginSuccess";
    }
}

然后

@Controller
@SessionAttributes({"user"})
public class InspectionTypeController {

   @RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
   public void addInspectionType(InspectionType inspectionType, @ModelAttribute User user) {
      System.out.println("User: "+ user.getUserDetails().getFirstName);
   }
} 

但是,如果您的原始代码不起作用,那么这也不起作用,因为您的 session 有其他问题。

关于java - Spring 3.0 设置和获取 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2227395/

相关文章:

java - Spring 和 DbUnit BeanCreationException Java

spring - 使用 Mockito 和 Spring MockMVC 在模拟中 stub 两个方法会抛出异常

mysql - MySQL中没有 session 变量的排名顺序分组数据?

php - 如何在单击提交按钮时创建 php session 变量?

java - 在一个 Eclipse 项目中集成 Java 和 Python 代码

java - Spark Java API,数据集操作?

Java-堆栈中的大写

java - Vert.x事件循环与单线程

javascript - 通过AJAX从$_SESSION发送变量到PHP进行密码更改,怎么做?

java - Spring Boot 2.x 中 HikariCP 默认有连接池吗?