java - 如何检查使用@SessionAttributes 创建的会话是否存在(Spring MVC)
问题描述
看看这段代码:
@Controller
@RequestMapping
@SessionAttributes("address")
public class HomeController {
@RequestMapping("/home")
public String welcome(Model model) {
Address address = new Address();
model.addAttribute("address", address);
return "welcome";
}
}
每次我到达 url“ /home ”时,都会调用welcome()方法,创建一个新对象Address,添加到模型中并保存在session中,名称为address。
检查会话“地址”是否已经存在的最佳方法是什么,以避免执行这行代码?
Address address = new Address();
model.addAttribute("address", address);
我使用这种方法,但我认为使用Spring features有更好和更具体的方法。
@RequestMapping
public String welcome(Model model, HttpServletRequest httpServletRequest) {
Address vecchioAddress = (Address)httpServletRequest.getSession().getAttribute("address");
if(vecchioAddress == null) {
Address address = new Address();
model.addAttribute("address", address);
}
}
谢谢
解决方案
尝试使用@SessionAttribute注释从会话中检索现有属性。
@RequestMapping
public String welcome(@SessionAttribute("address") Address address) {
// something....
}
推荐阅读
- java - Spring Boot 更改覆盖异常响应
- python - matplotlib中的pcolormesh重新缩放轴
- r - 给定另一列的三个最小值,我需要找到一列中的值
- jenkins - 如何使用 CURL 将多级单选参数传递给詹金斯作业?
- python - 如何确定两个熊猫系列是否在给定的时间间隔内
- python - 如何将 dict 值添加到字段等于 dict 键的 mongodb 文档?
- javascript - 制作 100 多个计数器的最有效方法是什么?
- python - 为什么我的 PCA 对旋转和轴交换不是不变的?
- javascript - 我想在页面加载时自动从我的代码文件夹中获取一个文件到我的 js 文件
- python - 如何在 Selenium Python 中获取标签名称?