Showing posts with label servlet. Show all posts
Showing posts with label servlet. Show all posts

Friday, 2 December 2016

Can I get HttpServletRequest instance during application startup

When the application is starting there are no HTTP servlet requests yet. In fact, Tomcat during bootup starts listening and accepting connections on 8080 port, but passes them to appropriate servlets only when all applications have successfully started. This means you cannot call yourself during startup since this will lead to deadlock - you are waiting for a response which is blocked by Tomcat that waits for you.
This also means that it is simply impossible (at least when Tomcat is taken as an exmaple) to obtain any HTTP servlet request during startup as there are absolutely no requests yet. Yes, mocking is the correct way, but I'm afraid if these libraries require an HttpServletRequest instance, simple mock might not be enough.

Reference : http://stackoverflow.com/questions/9130390/how-to-generate-an-httpservletrequest-during-spring-startup-for-a-bean-initialis

Thursday, 17 January 2013

Difference between attribute and parameter in Java

1. A "parameter" is a form field name/value pair passed from the HTML side of the world
   An "attribute" is a Java object name/value pair passed only through the internal JavaServer   processes. (I.e. it can come from a JSP or servlet but not an HTML page.) 

2. Parameter value is a String whereas attribute value is Object.

2. Parameters come from the client request.

 where as Attributes are set by the server side. For example, you can set a session or request attribute called userId to  indicate the current user

4. Parameters are read only i.e. generally can be retrieved, but not set. whereas 
 Attributes are read/write .You can also set attributes programaticly and retrieve them later. This is very useful in the MVC pattern.

5.
Description:


On the server side, the request.getParameter() will retrieve a value that the client has submitted in the First Name text field. Using this method you can retrive only one value. This method i.e. getParameter method is in ServletRequest interface which is part of javax.servlet package.
Request attributes (more correctly called "request-scoped variables") are objects of any type that are explicitly placed on the request object via a call to the setAttribute() method. They are retrieved in Java code via the getAttribute() method and in JSP pages with Expression Language references. Always use request.getAttribute() to get an object added to the request scope on the serverside i.e. using request.setAttribute().
Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programaticly and retrieve them later. This is very useful in the MVC pattern. For example, you want to take values from database in one jsp/servlet and display them in another jsp. Now you have resultset filled with data ready in servlet then you use setAttributemethod and send this resultset to another jsp where it can be extracted by using getAttributemethod.
Once a servlet gets a request, it can add additional attributes, then forward the request off to another servlet for processing. Attributes allow servlets to communicate with one another.


Note :
Later if you want, you can set parameters in request scope, which will be accessed in other included/forwarded servlet/JSP while using RequestDispatcher mechanism or can set parameter in session scope or application leval scope.Be careful here: there is no ServletRequest.setParameter() or HttpServletRequest.setParameter() method, nor is there a RequestDispatcher.addParameter() of RequestDispatcher.setParameter() method.

Two ways to get the object of HttpServletRequest



In Struts 2 , you can use the following two methods to get the HttpServletRequest object.However
Struts 2 documentation is recommended second method ServletRequestAware instead of ServletActionContext.

1. ServletActionContext

Get the HttpServletRequest object directly from org.apache.struts2.ServletActionContext.
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
 
public class LocaleAction{
 //business logic
 public String execute() {
  HttpServletRequest request = ServletActionContext.getRequest();
  return "SUCCESS";
 }
}

2. ServletRequestAware

Make your class implements the org.apache.struts2.interceptor.ServletRequestAware.
When Struts 2 ‘servlet-config interceptor is seeing that an Action class is implemented theServletRequestAware interface, it will pass a HttpServletRequest reference to the requested Action class via the setServletRequest() method.
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
 
public class LocaleAction implements ServletRequestAware{
 
 HttpServletRequest request;
 
 //business logic
 public String execute() {
  String param = getServletRequest().getParameter("param");
  return "SUCCESS";
 
 }
 
 public void setServletRequest(HttpServletRequest request) {
  this.request = request;
 }
 
 public HttpServletRequest getServletRequest() {
  return this.request;
 }
}
Struts 2 documentation is recommended ServletRequestAware instead of ServletActionContext.
Reference : http://www.mkyong.com/struts2/how-to-get-the-httpservletrequest-in-struts-2/

difference between request scope and session scope

http://stackoverflow.com/questions/4640721/servlets-setattribute-in-httpservletrequest-vs-setattribute-in-httpsession


setAttribute in HttpServletRequest vs setAttribute in HttpSession


The one sets an attribute in the request scope and the other sets an attribute in the session scope. The major difference is in the lifetime of the scope. The request scope ends when the associated response is finished. The session scope ends when the session has been timed out by the client or server. When a scope ends, then all of its attributes will be trashed and they aren't available in a different request or session.
You use the request scope to store data which should be specific to the HTTP request (for example, the database results based on a specific request, the success/error messages, etc). You use the session scope to store data which should be specific to the HTTP session (for example, the logged-in user, user settings, etc). All requests by the same client share the same session (thus, all different browser tabs/windows within the same client session will share the same server session).

When you set an attribute on the Request object, the variable is available only on the scope of the request. That variable can be accessed by other jsp/resources which you forward as part of this request.
While setting an attribute on session scope will be available to all the requests in the user session (unless you remove it from session).
So the major difference it boils down is the scope/life of the attribute.
Always try to use request scope variables unless you need to use it across the user session ex: like user roles. Keeping more data on the session with more concurrent users may lead to out of memory issues. Also if you are using the session sharing backed by a database (like you can do in websphere), it will lead to performance issues.

Wednesday, 20 June 2012

difference in redirect and forward

A Controller servlet can conclude either a forward or a redirect operation at the end of processing a request

RequestDispatcher vs sendRedirect



A Controller servlet can conclude either a forward or a redirect operation at the end of processing a request. Here are the basic differences between a requestDispatcher's forward() and sendRedirect() of the ServletResponse interface.
Forward
Since forward() method of RequestDispatcher is handled on the server , therefore the request and its associated session are available to the forwarded resource and you can pass data between them using request.setAttribute(). forward() separates the responsibilities for handling the requests among several components. This method generally sends a request and response object to resources (servlets or JSP's) of the same ServletContext. You can also decide to forward to one page in one condition and a different page in another. RequestDispatcher  transfers control immediately whenever the forward() method is called to the resource referenced by the RequestDispatcher.

sendRedirect

sendRedirect() method of a response object sends the url  to the browser that includes the parameter of sendRedirect() method Browser treats this a new request from the client. sendRedirect() forwards a requests to a resource outside of the current web application. Using sendRedirect is similar to open a new browser and type your url. A sendRedirect() also updates the browser history and transfers control only when the whole service method completes. There is only one way to pass data is through the session or using web parameters (url?name=value).

Note: Here are some more concepts that we must know:

  • RequestDispatcher.forward() and PageContext.forward() are effectively the same. PageContext.forward is a helper method that calls the RequestDispatcher method.
  • When you invoke RequestDispatcher.include(), the servlet engine transfers control of this HTTP request internally from your current servlet or JSP to another servlet or JSP or static file, while invoking response.sendRedirect() method sends an HTTP response to the browser to make another request at a different URL. In big applications, instead of forwarding to another servlet we generally use beans. Beans check a form, formats the response and returns to the servlet.