Announcement Announcement Module
Collapse
No announcement yet.
Hot to inject / autowire HttpServletResponse? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

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

    Comment


    • #3
      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?

      Comment

      Working...
      X