Im new in Spring and in frameworks in general …
I have some lines of code I want to execute in almost every handler.
For example I save my DB session and the authenticated user as httpSession attributes and for most of my handlers I have:
@RequestMapping(....)
public ModelAndView get(HttpSession ses){
User u = ses.getAttribute("currUser");
DBsession session = ses.getAttribute("DBsession");
if( u==null ) new ModelAndView("redirect:login");
...
}
Is there any way for spring to do that for me and get the DBsession and authenticated User objects directly as handler param ?
@RequestMapping(....)
public ModelAndView get(User u, DBsession session ){
...
}
The proper way to do this is to use a custom WebArgumentResolver, which cleanly extends
@RequestMappingannotated handler methods to resolve parameters. I used this mechanism to handle cleanly merging JPA entities and passing them to my controllers.You can see an example of doing this here and here or Google for more, there are plenty.