-1

I am writing Spring 3.1.0 MVC based application. The problem is: i want to put some objects in a singleton object (current HttpServletRequest and HttpSevletResponse) to use them in other objects(Spring Controllers). But couldn't do so. I tried to extend DispatcherServlet, overriding both doService and doDispatch. Also tried to implement own HandlerInterceptor. No result.

Where can I initialize my singleton objects? And where is Spring Frameworks's entry point and destroy point (i.e. like init() and destroy() methods or lifecycle)?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Sabyrzhan
  • 175
  • 2
  • 16

1 Answers1

1

The current HttpServletRequest and HttpServletResponse are available as method arguments to your controller methods:

@RequestMapping("/foo")
public String foo(HttpServletRequest request) {

}

I believe you can also @Inject them in your controller. A proxy will be injected, and each time you refer to them the current ones will be used. (I'm not 100% certain about this one)

A third option is to use the RequestContextHolder container, and get everything from there.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Yes. I know these ways. Thanks. But the thing is i am implementing a Facade pattern. That is, to access all my data, which i only can access from Spring framework, put in one object (e.g. spring message, get locales etc). That's why I want to put them in singleton. Do you know how to achieve the initialization of the singleton? – Sabyrzhan Jan 11 '12 at 19:29
  • controllers are singletons as well. I don't understand what exactly you want to achieve. – Bozho Jan 11 '12 at 19:33
  • Initialize my singleton, so i am able to access it in controllers. – Sabyrzhan Jan 11 '12 at 19:36
  • that alone is nothing special - you have a `@Component` (singleton by default) which you `@Inject` in your `@Controller` beans. – Bozho Jan 11 '12 at 19:37
  • OK. But what about current HttpServletRequest and HttpServletResponse i want to store in that singleton?! They are the main things. – Sabyrzhan Jan 11 '12 at 19:42
  • Try injecting them. OR use the `RequestContextHolder` to get them. Or simply use a `HandlerInterceptor` which gets them – Bozho Jan 11 '12 at 19:46
  • 1
    So you want to have a Singleton - which is by definition the only object of that kind in the JVM at that moment - to have a HttpServletRequest stored in it. Which is always request dependent, and therefore would mess up things if ever more than one request was made to you server at the same time. – Jukka Dahlbom Jan 11 '12 at 20:28
  • 1
    @JukkaDahlbom this is achievable through proxies, but I still don't get the point of it all :) – Bozho Jan 11 '12 at 21:38