使用 AutoWired HttpSession 时出现的问题:
LoginController 调用 LoginService,并传递 HttpServletRequest 作为参数。
我在其他几个带注释的类中像这样 Autowiring 了 HttpSession(但不在 LoginService 中):
@Autowired
private HttpSession httpSession;
在 LoginService 类中,如果我尝试通过调用 request.getSession(false)
来获取 session 在某些情况下我收到 null。
如果我尝试通过调用 request.getSession(true)
来获取 session 我最终得到两个 HttpSession 对象(一个在这里,另一个通过 AutoWiring)。
如果我在 LoginServic 类中 Autowiring HttpSession 并使用那里的 session ,那么我也会以两个 HttpSession 对象结束。
Autowiring 的 HttpSession 何时被创建?处理这种情况的最佳方法是什么?
谢谢!
最佳答案
LoginController 应该管理 Web Concern。
LoginService 应该管理身份验证问题,而不应该了解 Web 问题。
HttpSession 是 Web 域的一个关注点。因此,必须在管理 Web 关注点的类中进行管理 -> LoginController。
因此,LoginController 将声明 HttpSession 作为 Mapped 方法的参数,并从 HttpSession 中读取/写入所需内容,并将其作为 LoginService 上调用的方法的参数传递。
像这样的东西:
@Controller
public class ApplicationController {
@Autowired
private LoginService loginService;
@RequestMapping(value = "/login", method = POST)
public void Login(HttpSession httpSession) {
final String myAttribute = String.valueOf(httpSession.getAttribute("myAttribute"));
loginService.doWhatYouNeedToDo(myAttribute);
}
}
关于java - Spring MVC 什么时候会创建 Autowiring 的 HttpSession?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41151804/