在控制器中声明 HttpSession 对象 [英] Declaring HttpSession Object in Controller
问题描述
我们已经定义了一个控制器,需要声明HttpSession对象.我可以自动装配它或作为对象传递给方法.这两个选项有什么区别,哪个更可取?
We have defined a controller and need to declare the HttpSession object. I can autowire it or pass as an object to the method. What is the difference between the two options and which is preferable?
选项 1
@Controller
public class UserController {
@Autowired
HttpSession session;
..
..
}
选项 2
@Controller
public class UserController {
@RequestMapping(value="/user", method=RequestMethod.GET)
public @ResponseBody User getUser(HttpSession session) {
..
..
}
}
推荐答案
在控制器中,您应该使用 Option2.
In a Controller, you should use Option2.
会话从 http 请求开始,结束直到请求停止,但控制器在应用程序停止之前可用.所以你不应该在 Controller 中自动装配 HttpSession.
A session is start from a http request begin, end until the request stop, but the controller is available until the application stoped. So you should not autowired the HttpSession in Controller.
您可以像这样自动连接 http 会话的一种情况:
One of the situation you can autowired the http session like that:
@Component
@Scope(value=WebApplicationContext.SCOPE_SESSION)
public class CurrentUserHolder{
@Autowired
private HttpSession session;
public User currentUser() {
return this.get();
}
@Override
public User get() {
return (User)session.getAttribute("currentUser");
}
}
因此您可以在无法获取会话的服务中获取当前用户:
So you can get current user in a service which can not get the session:
@Service
public class UserService{
private @Autowired CurrentUserHolder currentUserHolder;
......
}
这篇关于在控制器中声明 HttpSession 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!