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?
Option 1
@Controller
public class UserController {
@Autowired
HttpSession session;
..
..
}
Option 2
@Controller
public class UserController {
@RequestMapping(value="/user", method=RequestMethod.GET)
public @ResponseBody User getUser(HttpSession session) {
..
..
}
}
In a Controller, you should use Option2.
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.
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;
......
}
If you have more than one methods in your controller which requires HttpSession, the Option 1 is preferrable. Otherwise, you can go with 'Option 2' instead of parameterizing it in every method.