Jan 11th, 2011, 09:31 AM
How can I have a common object in all Controllers
I am using Spring MVC 3.0 to develop a web application.
According to the architecture that I have got for my project, I would need to have the HttpServletRequest object in all the Controller methods that I have got in order to decide view path and for other frequently required attributes.
I know that I can have HttpServletRequest object as an argument in all the methods but that doesn't seem to be the best solution to me. It would be nice to have a reusable method somehow which I can call from any controller in order to get back the specified object from the Request object. Can someone please suggest me a way out?
Any help would be appreciated.
Jan 11th, 2011, 12:42 PM
Actually, I'd suggest turning the problem around. Rather than having each controller call something common, try putting your common behavior (setting request attributes, etc) in interceptors instead. Should simplify your controllers pretty significantly.
Hope this helps
Jan 12th, 2011, 03:57 AM
Thanks for your reply Don.
Further to your response I did some reading about how Interceptors work which was pretty helpful. However I still dont understand how could all the Controllers access a common object (say User) which is an attribute in Request object.
I can see the preHandle() method which returns boolean value but not sure how I could make the use of it in the right way.
Sorry if I sound a bit naive but still going through my learning curve here
Jan 12th, 2011, 10:11 AM
Well, there's two basic points here.
At the risk of repeating myself, anything you'd ordinarily be doing in multiple controllers (setting frequently provided attributes, etc) should be completely in the interceptor - don't put it in the controller at all.
Now if you have something in each controller that behaves differently based on request attribute values, you can just add it to the request in the interceptor and retrieve it in the controller. HOWEVER, if this attribute isn't being used in your views, you're better off just injecting a request-scoped bean into both your interceptors and controllers.
Hope this helps
Jan 13th, 2011, 07:18 AM
That's exactly what I need I think.... Interceptor and request-scoped beans.
I will give it a go and hopefully it should go on fine.
Thanks a lot.