At what point container creates request and response object? - java

When the client request comes, the container finds the correct servlet based on the URL and creates a pair of request and response objects.
According to me, the request and response objects only get created if the container finds valid servlet. That is, if there is no valid servlet found for the requested URL, then request and response objects don't get created.
However, I am not sure of this. Can anyone please confirm.

In chapter 12.1 Use of URL paths, the Servlet Specification states
The path used for mapping to a servlet is the request URL from the
request object minus the context path and the path parameters.
We can therefore assume that the request object (and possibly the response object) are created before any mapping logic is executed.
Note also that
Containers commonly recycle request objects in order to avoid the
performance overhead of request object creation.

Related

How does Tomcat maintain same session object across multiple request? [duplicate]

This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 3 years ago.
I have read that everytime an HTTP request is made to tomcat for a servlet it creates a new HTTPRequest Object and using that request object we can access session object and store information. This session object stores the information across multiple requests.
I want to understand if tomcat is creating a new HTTPRequest object for every request coming from a browser, then how it is able to attach same session object across multiple requests?
Apache is a servlet container.
The servlet container is attached to a webserver which listens on HTTP requests on a certain port number, which is usually 80. When a client (user with a web-browser) sends a HTTP request, the servlet container will create new HttpServletRequest and HttpServletResponse objects and pass it through the methods of the already-created Filter and Servlet instances whose URL-pattern matches the request URL, all in the same thread.
The request object provides access to all information of the HTTP request, such as the request headers and the request body. The response object provides facility to control and send the HTTP response the way you want, such as setting headers and the body (usually with HTML content from a JSP file). When the HTTP response is committed and finished, then both the request and response objects will be trashed. Source : https://howtodoinjava.com/server/tomcat/a-birds-eye-view-on-how-web-servers-work/
First of all, it is important to note that a servlet container does not necessarily create a new instance of HttpServletRequest for each request.
Tomcat, for example, recycles existing instances of HttpServletRequest as a performance optimization to reduce heap allocation. After a response has been committed, it resets the internal state of the existing HttpServletRequest instance and reuses that same instance for the next request. Same thing for the HttpServletResponse instance.
As a consequence, since this object is not immutable it's critically important to make sure that a HttpServletRequest object is not referenced anywhere outside the lifecycle of a single request.
To answer the OP's question: the HttpSession object is not something that's stored in a field of HttpServletRequest. HttpServletRequest.getSession() is just an API method, and the servlet engine typically implements it by retrieving the HttpSession from the session storage mechanism using the session ID provided by the request.
NOTE: there is also no guarantee that that the same actual instance of HttpSession will be returned for subsequent requests connected to the same session (see this question)
Although the HttpRequest object is created for each request the HttpSession object is persisted between the requests. The session is identified by JSESSONID cookie or request parameter (in case cookies are disabled) as explained in this answer.
As per Servlet 3.0 Specification:
HttpSession objects must be scoped at the application (or servlet
context) level. The underlying mechanism, such as the cookie used to
establish the session, can be the same for different contexts, but the
object referenced, including the attributes in that object, must never
be shared between contexts by the container.

Reading URL parameters when POST request with data arrives in Java Servlet

In Java servlets you read a JSON from a POST request e.g. via
new JSONObject(toString(httpRequest.getInputStream()))
Now additionally to the JSON I would like to specify parameters in the URL, they can be read via:
httpRequest.getParameterMap().get("someURLParam")
All is working (I'm using AJAX post requests and jetty for server side)
BUT
I'm concerned and confused if and when these two methods influence each other as the javadocs from javax.​servlet.​ServletRequest.getParamter(String) says:
If the parameter data was sent in the request body, such as occurs
with an HTTP POST request, then reading the body directly via
ServletRequest.getInputStream or ServletRequest.getReader can
interfere with the execution of this method.
What does it mean in my case? Or do they only interfere if content type is x-www-form-urlencoded? Or only if using getParameter and the method getParameterMap is fine?
If you are only using getParameter/getParameterMap, you will be fine. This is because, behind the scenes, those methods may call getInputStream. The spec says MAY because it's up to the implementation, so the behavior may vary from one container to another.
If your content isn't form encoded, or you are processing a GET request, etc., getParameter/getParameterMap only needs to get the parameters from the query string, so it makes sense that Jetty wouldn't read the body in those cases.

How to get Server Name, Port and Context

I have Java Web app.
I need get its URL where it is running (e.g. http://myserver:8080/mycontext).
I need it because I want to be able construct URL on some resource, that has been created.
e.g. By soap request was created resource /myresource and I need insert into soap response reference on this resource (http://myserver:8080/mycontext/myresource)
And I need to be able return URL on resource even when message come from JMS.
Is it possible to determine application URL during startup? e.g. in ServletContextListener.
Or how it is beeing solved?
You can get all those from the HttpServletRequest object, if you can get a hold of it.

How servlet handle multiple request from same jsp page

Sorry friends if this question is very easy but i am confuse i unable to find out solution.
As we all know in spring MVC framework we create controller which will handle multiple request from same page using #requestmapping annotation.
but same thing i want to do in servlet how can i do ?
Suppose i have a jsp which which will contain a jqgrid,and two forms i want to use only one servlet to load the data into jqgrid and that servlet only will handle request from both the form . Since we have only doGet and doPost in servlet how one servlet fulfill all three request. Hope you understand my question if you have and link where i get sample or and tutorial link plz reply me
Well, the only easy way to do this would be to use a request parameter to control how the processing happens.
In a very basic example, you may have something like a requestType value that gets passed as either part of the query string or the request body. You would assign values of 1-3 (or 0-2) with each value indicating a different type of request. Your servlet would then parse the request accordingly.
This actually is how the DispatcherServlet in SpringMVC works. There's only one servlet class instance and when a request comes in, it examines the query string along with other parts of the request to determine which controller should handle the request.

Servlet include swallows HTTP headers in Tomcat

I have a servlet that does a request dispatcher include of another servlet.
The included servlet sets headers that I would like to read in the including servlet. So I pass in a custom HTTPResponse object in the include() method which captures all feedback activity from the servlet.
The problem is that the headers are not being set in my custom response. I've run in debug and examined what looks like Tomcat wrapping my custom response object with its own response object. The setHeader calls go to this wrapping class and never propagate to my custom response object.
I imagine Tomcat does this to protect the client from headers being set in the wrong place. The funny thing is that the same approach works the way I'd expect in Jetty.
It's been a while since I've done Servlets seriously so I'm struggling a bit here. I'm trying to figure out how to read the response headers from a servlet that's invoked via dispatcher.include().
From the Servlet specifications section SRV.8.3:
The include method of the RequestDispatcher interface may be called at any time.
The target servlet of the include method has access to all aspects of the request
object, but its use of the response object is more limited.
It can only write information to the ServletOutputStream or Writer of the
response object and commit a response by writing content past the end of the
response buffer, or by explicitly calling the flushBuffer method of the
ServletResponse interface.
It cannot set headers or call any method that affects
the headers of the response. Any attempt to do so must be ignored.
How about setting your values for the calling servlet in request scope, with request.setAttribute(...) and then reading it from there once you return? Could that work?

Categories