While creating a servlet, i get confused between request and response methods.
What should be my perspective while writing a servlet, should i view the servlet and think as servlet is making its request and response or do the same from the client side.
For example,
Why is response.getWriter() from response side?
Similarly for certain response and request methods.
Don't get confused.
The request is coming from the client side.
The response is what the servlet going to send to the client side.
So you will need to write something to response most of the time. This is where you get a writer object. So response.getWriter() gives you the writer object.
The servlet does not itself create the response and request objects. The container creates them and forwards these objects to the matching servlet based on the client's http request.
Related
I'm building a Java back-end using Spring with Jersey, where I want to send a multipart response to the client.
I have a GET call that looks something like this:
#Path("/status/{requestID}")
#GET
public Response getStatus(#PathParam("requestID") String requestId) {
MDC.put("myRequestID", requestId);
// Do some processing
return response;
}
I use MDC to add request ID and other information that I need in my logs. Now the response that I create is Multipart, and since Jersey internally converts this Multipart response to HTTP response, during this processing I have certain callbacks which logs messages and I want the MDC to be populated at that time, with whatever was put in my getStatus call.
Now, usually I would call MDC.clear() before returning status in my getStatus call. But, now that I want to wait for Jersey to complete processing, I cannot do that.
Is there any callback that Jersey provides once the HTTP response processing is complete, where I can do this cleanup?
I want to send values from jsp1.jsp to jsp2.jsp but redirect jsp1.jsp to jsp3.jsp . I used the following code in servlet for jsp1
response.sendRedirect("welcome1.jsp");
request.setAttribute("usern",user);
RequestDispatcher rd = request.getRequestDispatcher("afterlogin.jsp");
rd.forward(request,response);
but it keeps on giving this error "org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP".
you can use the possiblites of sessions in those case so you can access the parameter in jsp2 and redirect the jsp 1 to 3
https://www.javatpoint.com/servlet-http-session-login-and-logout-example
http://java.candidjava.com/tutorial/Servlet-Jsp-HttpSession-Login-logout-example.htm
You can use a HttpSession object as a user session, or use the ServletContext object for sharing global application information. Then use methods getAttribute (String attb) and setAttribute (String attb, String value) for sharing information within JSPs. The issue when you use a request is that the domain of the request is constraining you to use this information only when you receive this request.
You can also use JavaBeans to share information within JSPs
EDIT: Have you included your Java code inside a scriptlet? Using <% your code here %>
when you are using the sendRedirect function it will immediately redirect to that page it will not read next line code.
So according to your code your compiler is smart enough to check it so it is giving you an error.
please see below
1) SendRedirect ():
This method is declared in HttpServletResponse Interface.
Signature: void sendRedirect(String url)
1)In case of sendRedirect request is transfer to another resource to different domain or different server for further processing.
2)When you use SendRedirect container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
3)In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
4)SendRedirect is slower because one extra round trip is required because completely new request is created and old request object is lost.Two browser request required.
5)But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.
2) Forward():
This method is declared in RequestDispatcher Interface.
Signature: forward(ServletRequest request, ServletResponse response)
1)When we use forward method request is transfer to other resource within the same server for further processing.
2)In case of forward Web container handle all process internally and client or browser is not involved.
3)When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request
4)Using forward () method is faster then send redirect.
5)When we redirect using forward and we want to use same data in new resource we can use request. setAttribute() as we have request object available.
more in : https://www.javatpoint.com/q/3577/difference-between-requestdispatcher-and-sendredirect
I have two request filters and one request interceptor as follows:
#Provider
#RequestLogger
#Priority(100)
public class LogRequestFilter implements ContainerRequestFilter {
...
}
#Provider
#OracleSessionChecker
#Priority(300)
public class CheckOracleSessionFilter implements ContainerRequestFilter {
...
}
#Provider
#RequestChecker
#Priority(200)
public class CheckRequestInterceptor implements ReaderInterceptor {
...
}
I have JAX-RS web services that use these filters and interceptor. The following is one example web service method.
#POST
#RequestLogger
#RequestChecker
#OracleSessionChecker
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("Logout")
public Response logout(#Context HttpServletRequest request, Parameters inputs) {
...
}
From the priorities given, I would think that the order that the filters/interceptor are called would be:
LogRequestFilter, CheckRequestInterceptor, CheckOracleSessionFilter.
But the actual order that they are called is:
LogRequestFilter, CheckOracleSessionFilter, CheckRequestInterceptor.
Why is the CheckRequestInterceptor called last even though its priority, 200, is in the middle?
How can I make them called in the order that I want (that is, LogRequestFilter, CheckRequestInterceptor, CheckOracleSessionFilter)?
Thanks in advance.
All RequestFilters are executed based on their priorities before any RequestInterceptors (which are then executed based on their priorities).
The simplest explanation I can think of is if you had the following files in a folder:
F-100
F-300
I-200
I-200 doesn't come before F-300 (even though 200 is before 300) because 'F's are sorted before 'I's.
You can't mix filter and interceptor execution order, see Jersey Documentation:
10.4. Filter and interceptor execution order
Let's look closer at the context of execution of filters and interceptors. The following steps describes scenario where a JAX-RS client makes a POST request to the server. The server receives an entity and sends a response back with the same entity. GZIP reader and writer interceptors are registered on the client and the server. Also filters are registered on client and server which change the headers of request and response.
Client request invoked: The POST request with attached entity is built on the client and invoked.
ClientRequestFilters: client request filters are executed on the client and they manipulate the request headers.
Client WriterInterceptor: As the request contains an entity, writer interceptor registered on the client is executed before a MessageBodyWriter is executed. It wraps the entity output stream with the GZipOutputStream.
Client MessageBodyWriter: message body writer is executed on the client which serializes the entity into the new GZipOutput stream. This stream zips the data and sends it to the "wire".
Server: server receives a request. Data of entity is compressed which means that pure read from the entity input stream would return compressed data.
Server pre-matching ContainerRequestFilters: ContainerRequestFilters are executed that can manipulate resource method matching process.
Server: matching: resource method matching is done.
Server: post-matching ContainerRequestFilters: ContainerRequestFilters post matching filters are executed. This include execution of all global filters (without name binding) and filters name-bound to the matched method.
Server ReaderInterceptor: reader interceptors are executed on the server. The GZIPReaderInterceptor wraps the input stream (the stream from the "wire") into the GZipInputStream and set it to context.
Server MessageBodyReader: server message body reader is executed and it deserializes the entity from new GZipInputStream (get from the context). This means the reader will read unzipped data and not the compressed data from the "wire".
Server resource method is executed: the deserialized entity object is passed to the matched resource method as a parameter. The method returns this entity as a response entity.
Server ContainerResponseFilters are executed: response filters are executed on the server and they manipulate the response headers. This include all global bound filters (without name binding) and all filters name-bound to the resource method.
Server WriterInterceptor: is executed on the server. It wraps the original output stream with a new GZIPOuptutStream. The original stream is the stream that "goes to the wire" (output stream for response from the underlying server container).
Server MessageBodyWriter: message body writer is executed on the server which serializes the entity into the GZIPOutputStream. This stream compresses the data and writes it to the original stream which sends this compressed data back to the client.
Client receives the response: the response contains compressed entity data.
Client ClientResponseFilters: client response filters are executed and they manipulate the response headers.
Client response is returned: the javax.ws.rs.core.Response is returned from the request invocation.
Client code calls response.readEntity(): read entity is executed on the client to extract the entity from the response.
Client ReaderInterceptor: the client reader interceptor is executed when readEntity(Class) is called. The interceptor wraps the entity input stream with GZIPInputStream. This will decompress the data from the original input stream.
Client MessageBodyReaders: client message body reader is invoked which reads decompressed data from GZIPInputStream and deserializes the entity.
Client: The entity is returned from the readEntity().
It is worth to mention that in the scenario above the reader and writer interceptors are invoked only if the entity is present (it does not make sense to wrap entity stream when no entity will be written). The same behaviour is there for message body readers and writers. As mentioned above, interceptors are executed before the message body reader/writer as a part of their execution and they can wrap the input/output stream before the entity is read/written. There are exceptions when interceptors are not run before message body reader/writers but this is not the case of simple scenario above. This happens for example when the entity is read many times from client response using internal buffering. Then the data are intercepted only once and kept 'decoded' in the buffer.
I'm using cross-context to call a servlet in another server application: Servlet /bar from server application 'A' calls /foo servlet on server application 'B'.
I'm using this very nice solution, just as in the Abhijeet Ashok Muneshwar answer, I forward the request from server application A to the /foo servlet on server application B.
I'm using the class RequestDispatcher () to send a request, but the response is returned in the same call?
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
How can I process and return the response from server application B in A's servlet.
Thanks.
If you use a forward, that passes control to the target of the forward. The other option with a RequestDispatcher is to do an include.
If you want more control than that, you'll have to use an HTTP client to retrieve the response and then apply whatever processing you want to but using an HTTP client this way is not something I'd recommend. You'd be better off refactoring your application so you can use RequestDispatcher.include.
In Java, the attribute field of a HttpServletRequest object can be retrieved using the getAttribute method:
String myAttribute = request.getAttribute("[parameter name]");
Where the HttpServletRequest attribute data is stored in a raw HTTP request? Is it in the body of the request?
For example, I'm trying to create a raw GET HTTP request that will be sent to my servlet using some client program. My servlet.doGet() method would be something like this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
String myAttribute = request.getAttribute("my.username");
...
}
Where should I put the 'my.username' data in the raw HTTP request so that the 'myAttribute' String receives the value "John Doe" after the attribution?
Just to be clear as I think #Jon's answer doesn't make it perfectly clear. The values for getAttribute and setAttribute on HttpServletRequest are not present on what is actually sent over the wire, they are server side only.
// only visible in this request and on the server
request.getAttribute("myAttribute");
// value of the User-Agent header sent by the client
request.getHeader("User-Agent");
// value of param1 either from the query string or form post body
request.getParameter("param1");
To add to #gid's answer, attributes are not present in any way in the HTTP request as it travels over the wire. They are created (by your code) when processing the request. A very common use is to have a server set (aka create) some attributes and then forward to a JSP that will make use of those attributes. That is, an HTTP request arrives and is sent to a Servlet. The Servlet attaches some attributes. Additional server-side processing is done, eventually sending the page to a JSP, where the attributes are used. The response is generated in the JSP. The HTTP request and the HTTP response do not contain any attributes. Attributes are 100% purely server-side information.
When a single given HTTP request has completed, the attributes become available for garbage collection (unless they are persisted in some other location, such as a session). Attributes are only associated with a single request object.
I think what he is really asking is "how do I get parameteres into my program", not attributes. If that is the question, then send parameters in the GET request as part of the URL (after a question mark, http://myhost.com/myapp?name=joe&age=26) then retrieve them using request.getParameter("name") and request.getParameter("age"), or whatever you need.