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()
.
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder. getRequestAttributes()) . getRequest(); Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)
Pass it to the constructor: public class XmlParser{ final private HttpServletRequest request; public XmlParser(HttpServletRequest request) { this. request = request; } // use it in othe methods... }
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With