Wednesday, May 31, 2006

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.

Saturday, May 27, 2006

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);
}
}

Handling Servlet Exceptions (using web.xml file)

1). Handling all Exceptions

In this you have to write the try catch block in the service method which will catch all the exceptions. In the catch block we have to throw the servlet exception.

public void service( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// some code which throws exception
} catch (Exception e) {
throw new ServletException(e.getMessage());
}
}

And after this we have to modify the web.xml file and include following lines -

<error-page>
<location>/errorPage.html</location>
</error-page>

2). Handling Exceptions by HTML Error Code

We can also handle a particuler HTML error by including the error-code in web.xml.

<error-page>
<error-code>500</error-code>
<location>/errorPage.html</location>
</error-page>

3). Handling Exceptions by java Exception Type

In this you have to write the try catch block in the service method which will catch a particular exception. In the catch block we have to throw that exception.

public void service( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// some code which throws exception
} catch (NumberFormatException ne) {
throw new NumberFormatException(ne.getMessage());
}
}

And after this we have to modify the web.xml file and include following lines -

<error-page>
<exception-type>
java.lang.NumberFormatException</exception-type>
<location>/errorPage.html</location>
</error-page>

Monday, May 22, 2006

Changing the Default welcome file

change/edit web.xml from following location($CATALINA_HOME/conf,)

and add/edit following lines

<welcome-file-list>
<welcome-file>now_see_this.jsp</welcome-file>
<welcome-file>page1.html</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

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.

Forward is faster compared to Redirection.

Servlet Chaining

Servlet chaining is a mechanism by which request. response objects are communicated through a series of servlets. this is almost similar to this redirect and forward in Jsps. response from one servlet is passed again as a request object to another servlet to perfom one more task.