Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing HttpServletRequest object in a normal Java class from Spring

I have a normal Java class in a Spring MVC 3.06 web application.

In this class I would like to inject or get hold of the HttpServletRequest object in a method.

I know I can pass this around, but I was wondering how can I get hold of the request without passing it in to the method. Perhaps using annotations or similar?

Also, what are the "real" concerns with getting hold of the request this way, except some peoples opinions of it being ugly coding. I mean, is it unstable to access it this way?

Preferably non application server dependent way.

I have seen

(HttpServletRequest) RequestContextHolder.getRequestContext().getExternalContext().getNativeRequest() 

but this doesn't seem to work for Spring MVC 3.06 . RequestContextHolder doesn't have the method getRequestContext().

like image 596
mjs Avatar asked Mar 19 '12 09:03

mjs


People also ask

How do I get HttpServletRequest in spring?

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder. getRequestAttributes()) . getRequest(); Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

How do I pass HttpServletRequest in Java?

Pass it to the constructor: public class XmlParser{ final private HttpServletRequest request; public XmlParser(HttpServletRequest request) { this. request = request; } // use it in othe methods... }

What is HttpServletRequest in spring?

Spring Boot HttpServletRequest Logging Filter. A Request Logging Filter for Spring Boot applications, that allows you to read the request body multiple times. The request body is cached using an overridden HttpServletRequestWrapper. Then a reader that allows the client to read the body multiple times is returned.

Which method of the HttpServletRequest object is used?

Object of the HttpServletRequest is created by the Servlet container and, then, it is passed to the service method (doGet(), doPost(), etc.) of the Servlet.


1 Answers

Use

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

I'm not sure where you got RequestContextHolder.getRequestContext(), that's completely wrong.

is it unstable to access it this way?

No, it's stable enough, assuming you're always running the code as part of an HttpServlet request thread. The main issue is that yes, it's ugly, and it makes your code hard to test. That is reason enough not to use it.

If you must use it, then decouple it from your code, e.g.

public void doSomething() {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    doSomething(request);
}

void doSomething(HttpServletRequest request) {
   // put your business logic here, and test this method
}
like image 61
skaffman Avatar answered Oct 21 '22 01:10

skaffman