Results 1 to 3 of 3

Thread: Hot to inject / autowire HttpServletResponse?

Hybrid View

  1. #1
    Join Date
    Apr 2011
    Posts
    6

    Default Hot to inject / autowire HttpServletResponse?

    I have a bean which provides easy access on the web server side to the HttpServletResponse and HttpServletRequest objects of the current request.

    To get the HttpServletRequest I simply added this to web.xml:

    Code:
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <listener>
      		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    	</listener>
    Then referred to the object in the bean by:
    Code:
    public HttpServletRequest getRequest() {
    		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    		return attr.getRequest();
    	}
    I am having trouble locating an easily efficient way to access the HttpServletResponse. Can anyone help?

    Thanks
    Gene

  2. #2
    Join Date
    Mar 2011
    Posts
    18

    Default Spring controller

    I do not know such method for HttpServletResponse but this obviously is Thread-local-storage pattern. You could also implement it with java.lang.ThreadLocal and an own ServletFilter/Listener by yourself but this is not necessary.

    I suggest using a Spring web controller. Every annotated method inside your Spring controller will then be called when requesting a matching url pattern.
    Such controller method can also have annotated parameters and parameters with known types being relevant for the request as HttpServletRequest and HttpServletResponse. The result can also be annotated and can represent a view id that will be rendered after computing domain logic or the full string that will be output.

    regards,
    Max

  3. #3
    Join Date
    Sep 2009
    Location
    Vilnius, Lithuania
    Posts
    118

    Default

    The big question here is where you want to access HttpServletRequest.
    If you need it in your presentation layer, then you should get a grip of it in one of your controllers or servlets and pass it along to whatever object needs it.

    If, on the other hand, you need HttpServletRequest in lower layers of your application (e.g. Services, Repositories, etc.), then it is an indication that your business code is too tightly coupled to presentation logic and probably has to be redesigned.

    So which one is the case?

Tags for this Thread

Posting Permissions

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