Pages

servlets

Wednesday, 28 March 2012


Listening to HttpSession Events
The javax.servlet.http package provides two interfaces that you can implement to listen to HttpSession events: HttpSessionListener and HttpSessionAttributeListener.
The first enables you to listen to a session's life cycle events, that is, the event that gets triggered when an HttpSession object is created and the event that is raised when an HttpSession object is destroyed. The second interface, HttpSessionAttributeListener, provides events that get raised when an attribute is added to, removed from, or modified in the HttpSession object.

The HttpSessionListener Interface :-

public void sessionCreated(HttpSessionEvent se)
public void sessionDestroyed(HttpSessionEvent se)

The HttpSessionEvent class is derived from the java.util.EventObject class. The HttpSessionEvent class defines one new method called getSesssion that you can use to obtain the HttpSession object that is changed.

The HttpSessionAttributeListener Interface :-

public void attributeAdded(HttpSessionBindingEvent sbe)
public void attributeRemoved(HttpSessionBindingEvent sbe)
public void attributeReplaced(HttpSessionBindingEvent sbe)

The HttpSessionBindingEvent is derived from the HttpSessionEvent class so it inherits the getSession method. In addition, the HttpSessionBindingEvent class has two methods: getName and getValue. The signatures of the two methods are as follows:

public String getName()
public Object getValue()

The getName method returns the name of the attribute that is bound to an HttpSession or unbound from an HttpSession. The getValue method returns the value of an HttpSession attribute that has been added, removed, or replaced.
Methods of ServletContextListener
public void contextInitialized(ServletContextEvent sce);
public void contextDestroyed(ServletContextEvent sce);

Utilizing the contextInitialized method is similar to writing code in a servlet's init( ) method. However, using application events make the codes available throughout the whole application, not only from inside a servlet.
Both methods of the ServletContextListener interface pass a ServletContextEvent class. This class has the following signature:

public class ServletContextEvent extends java.util.EventObject

The ServletContextEvent has only one method: getServletContext.

This method returns the ServletContext that is changed.Note that before you can set a ServletContext attribute, you first need to obtain the ServletContext object using the getServletContext method of the ServletContextEvent class.

ServletContext servletContext = sce.getServletContext();

Listening to ServletContextAttributeListener :-

public void attributeAdded(ServletContextAttributeEvent scae)
public void attributeRemoved(ServletContextAttributeEvent scae)
public void attributeReplaced(ServletContextAttributeEvent scae)

The attributeAdded method is called when a new attribute is added to the ServletContext object. The attributeRemove method is called when an attribute is removed from the ServletContext object, and the attributeReplaced method is invoked when an attribute in the ServletContext object is replaced.Note that the attributeReplaced also is called when the attributeAdded is triggered.
Session Object
The getSession method of the javax.servlet.http.HttpServletRequest interface has two overloads.
They are as follows:
• HttpSession getSession()
• HttpSession getSession(boolean create)

The first overload returns the current session associated with this request, or if the request does not have a session identifier, it creates a new one.
The second overload returns the HttpSession object associated with this request if there is a valid session identifier in the request. If no valid session identifier is found in the request, whether a new HttpSession object is created depends on the create value. If the value is true, a new HttpSession object is created if no valid session identifier is found in the request. Otherwise, the getSession method will return null.
include() and forward()
The include method is used to include content from another resource, such as another servlet, a JSP page, or an HTML page.

public void include(javax.servlet.ServletRequest request, javax.servlet.ServletResponse
response) throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher rd = request.getRequestDispatcher("SecondServlet");
rd.include(request, response);
}

If you are including from a doPost method, the doPost method of the second servlet will be invoked. If including from a doGet method, the doGet method of the second servlet will be called.

The forward method is used to forward a request from one servlet to another.

public void forward(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher rd = request.getRequestDispatcher("SecondServlet"); rd.forward(request, response);
}

Unlike the include method, the forward method of the RequestDispatcher interface may be called only by the calling servlet if no output has been committed to the client. If output exists in the response buffer that has not been committed, the buffer must be cleared before the target servlet's service method is called. If the response has been committed prior to calling the forward method, an IllegalStateException will be thrown.
Handling Servlet Exceptions (using RequestDispatcher)
In this we have to just write the RequestDispatcher code in the catch block.

public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//some code which throws exception
} catch (Exception e) {
RequestDispatcher dispatcher = getServletContext.getRequestDispatcher("/error.jsp");
dispatcher.forward(request, reponse);
}
}
sendRedirect() and forward()
Difference between sendRedirect() and forward() "Redirect is an indication from the server to the browser to redirect to the defined URL. When a request comes from the browser, the server receives the request, fetches the URL to be redirected and again informs the browser to direct to that particualr URL, then browser redirects to that URL. On the whole, this is a round about process since request is forwarded twice first frm browser to server and server back to Browser.

Forward is a mechanism in which the server directly directs the browser to the new url deifined and since its an implicit jsp object, the whole action is govened by the container /server.

Some more Explanation :-

Both the sendRedirect and forward methods bring the user to a new resource. There is a fundamental difference between the two, however, and understanding this can help you write a more efficient servlet.
The sendRedirect method works by sending a status code that tells the browser to request another URL. This means that there is always a round trip to the client side. Additionally, the previous HttpServletRequest object is lost. To pass information between the original servlet and the next request, you normally pass the information as a query string appended to the destination URL.
The forward method, on the other hand, redirects the request without the help from the client's browser. Both the HttpServletRequest object and the HttpServletResponse object also are passed to the new resource.


J2EE: SERVLET: Class GenericServlet vs Class HttpServlet
Class GenericServlet :

·                    It is an abstract class which defines a generic and protocol independent servlet. Here, protocol independent means, by default, it doesn’t contain inherent support for any particular type of protocol, but it can be extended to provide implementation of any protocol.

·                    Class GenericServlet implements Interface Servlet and Interface ServletConfig  and it belongs to javax.servlet package.

·                    It offers simpler version of the servlet life cycle methods init() and destroy() and the methods of ServletConfig. That’s why, it makes writing a servlet easier.

·                    Here, the method service(ServletRequest req, ServletResponse res) is abstract, so the subclasses must override it. And this is also the reason why the GenericServlet is an abstract class.




Class HttpServlet :

·        It is also an abstract class which defines HTTP prototype dependent servlet. That means we need to extend it to write a HTTP servlet for the use of the web.

·        Class HttpServlet is a subclass of Class GenericServlet and it belongs to javax.servlet.http package.

·        As it’s an abstract class, a subclass of it must override at least 1 method, generally one of these doGet(), doPost(), doPut(), doDelete(), init(), destroy(), getServletInfo().

·        Class HttpServlet has two service() methods - one is public void service(ServletRequest req, ServletResponse res) which dispatches client request to protected void service(ServletRequest req, ServletResponse resp) which again dispaches the request to the doXXX methods (like doGet(), doPost(), etc.).


 

Most Reading