Results 1 to 5 of 5

Thread: How can I have a common object in all Controllers

  1. #1
    Join Date
    Jan 2011
    Posts
    4

    Default How can I have a common object in all Controllers

    Hi

    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.

    Many Thanks
    Rana

  2. #2
    Join Date
    Nov 2005
    Posts
    113

    Default

    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
    - Don

  3. #3
    Join Date
    Jan 2011
    Posts
    4

    Default

    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

    Many Thanks.

  4. #4
    Join Date
    Nov 2005
    Posts
    113

    Default

    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
    - Don

  5. #5
    Join Date
    Jan 2011
    Posts
    4

    Default

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •