HttpServletRequest Object in Simple java file - spring

I am working on the Web Project, and i want to get the information of the request object in our simple java program which is not extending the HttpServlet class.
The same problem i am facing in the #init() of servlet , i want to call some functions in init() in that i need request object , but i am not getting how can i do this functionality.
please do not post any answer with related to the Spring technology :)
I googles alot but didn't find anything for this.Please help me out.

First of all, HttpServletRequest and HttpServletResponse are interfaces.
The implementation classes for these interfaces are provided
by the application server (server container) vendor (like Tomcat, JBoss, Glassfish,
etc..).
When the application server (where the your web application is
deployed), receives the request from the client, the objects for the
HttpServletRequest and HttpServletResponse implementation classes are
created. And the creation of these objects happens for each hit
(request) from client.
In general, these request/response objects (created by container) will be passed to the HttpServlet class as method parameters, from which we will retrieve the data the client intended to send to the server/servlet methods inside doGet() or doPost() (using request.getParameters() method).
Also refer below docs to know more about the HttpServletRequest and HttpServletResponse are interfaces.
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html

Related

HttpServletRequest throws error when used within Aspect

I have a method which has an aspect. When I try to #Autowire HttpServletRequest, and use request.getHeader(something), I get this error -
No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
How do I fix this? I tried using RequestContextHolder, but upon debugging I still see null. How do I use the RequestContextListener when my project has no web.xml.
Request Header can be accessed using HttpServletRequest below way.
private static HttpServletRequest getRequest() {
return((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
public static String getApiTraceId() {
return getRequest().getHeader(something);
}
Aspect annotations spins a new thread which is different from the one httpservlet is available in. This is why request was not available within the #ASpect. To resolve it, call the request object BEFORE the aspect method, cache it and call the same method as before.

Using Server Request and Response filters for ThreadLocal storage in a RestEasy based service

I am currently working on a RESTeasy based RESTful service. I have a filter class which serves as a server request filter as well as a server response filter (i.e. it implements ContainerRequestFilter and ContainerResponseFilter interfaces).
At the beginning of the request, I use the filter to put an object into ThreadLocal. This object is used by the resources throughout the request. At the end of the request, before sending out the response, the filter removes the object from ThreadLocal.
My question is that is there a guarantee that the the request filter, the resource and the response filter will all execute in the same thread? Is there a possibility that after the request filter puts the object into ThreadLocal, a different thread will execute the request (and thus not have access to the object)?
I was sure that this was the case but then I saw this http://jersey.576304.n2.nabble.com/Does-filter-method-of-ContainerRequestFilter-run-in-resource-method-thread-td7582648.html (official Jersey forum) and now I have doubts.
javax.ws.rs.container.ContainerRequestContext.setProperty(...)
and
javax.ws.rs.container.ContainerRequestContext.getProperty(...)
are probably the right approach. The javadoc states:
In a Servlet container, the properties are synchronized with the ServletRequest and expose all the attributes available in the ServletRequest. Any modifications of the properties are also reflected in the set of properties of the associated ServletRequest.

How to get source address / ip from inside ContainerResponseFilter

I'm writing a logging filter that logs all HTTP requests / responses for a web app running in Jersey. ContainerResponseFilter seems to a straight forward solution and I've managed to get it to work.
Next step is to log the IP of the requests. Is there a way to do that from inside the ContainerResponseFilter ?
Short answer:
#Provider
public class YourContextFilter implements ContainerRequestFilter {
#Context
private HttpServletRequest sr;
#Override
public synchronized void filter(ContainerRequestContext request) throws IOException {
/*
* Returns the Internet Protocol (IP) address of the client or
* last proxy that sent the request. For HTTP servlets, same as
* the value of the CGI variable REMOTE_ADDR.
*/
String ip = sr.getRemoteAddr();
// ... log it ...
}
}
EDIT
(regarding the wish for a more detailed answer)
Afaig:
The #Context annotation allows to inject JAX-RS–specific components (one might say you are able to inject contextual information objects). JAX-RS itself is a Java based specification for RESTful Web Services over HTTP protocol. So we are able to inject stuff like:
javax.ws.rs.core.UriInfo
javax.ws.rs.core.Request
javax.ws.rs.core.SecurityContext
and also
javax.servlet.http.HttpServletRequest
In the IOC Chapter of the Jersey docs, you will find these notes:
[...] Jersey implementation allows you to directly inject HttpServletRequest instance into your JAX-RS components [...] - https://jersey.java.net/nonav/documentation/latest/user-guide.html#d0e2401
[...] The exception exists for specific request objects which can injected even into constructor or class fields. For these objects the runtime will inject proxies which are able to simultaneously server more request. These request objects are HttpHeaders, Request, UriInfo, SecurityContext. These proxies can be injected using the #Context annotation. [...]
[...] When deploying a JAX-RS application using servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available using #Context. [...]
And if you do so, you inject in fact a Proxy named org.apache.catalina.connector.RequestFacade (link). This proxy functioned as your direct hotline to your Coyote (HTTP Connector) and thereby to the Coyote request object (link).
Hope this was helpful somehow :) - Have a nice day.

HttpservletRequest and response in Spring JMS listener

Can someone tell whether is there a way to get HttpServletRequest and HttpServletResponse in Spring JMS listener class? My JMS listener is defined in springContext.xml file.
First of all you don't have access to HTTP servlet request and response within JMS listeners. These are completely independent modules that can even reside on different physical servers.
You can use MockHttpServletRequest and MockHttpServletResponse from spring-test.jar - but they are meant to be used within unit/integration tests, not in production code.
I would really like to see your code that requires MockHttpServletRequest and response. My guess is that it can be refactored or redesigned to use only relevant fields from the above, like request URL or user name.
I ended up using JAXDispatcher to invoke my service, from my JMS listener.
jaxbDispatcher.doGET(null, url, null, "application/xml", true);

Spring MVC, how to have a controller handler handle all the requests before the mapped handlers?

I've wrote a web app with its brave controllers and handler mapping, everything with Spring 3.0 and controller annotations. Now turns out that I need simple and custom autentication. I don't want to use ACEGI for the moment, because I've no time to learn it. I'd like ideally that I could have a routine that gets called before every mapped handler, gets from the HttpSession the userId, checks if he is logged in and the session key and if not redirects to a login page. I've been thinking about an interceptor... the problem is that you have to use HandlerInterceptorAdapter, which has the following method:
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
that won't let me access the HttpSession associated with the request. How do I solve this?
Are you sure? You should be able to obtain the session through request.getSession().

Resources