18 More Servlet API

Pravin Jain

epgp books

 

Introduction

 

In this module we will develop a BaseServlet which we can use in all our applications. In the servlet API also there is a similar class known as GenericServlet. We will try to understand the class called GenericServlet. This class is part of javax.servlet package. In the earlier module we have developed our first Servlet class which was the HelloServlet.

 

Need for a base servlet class

 

In the earlier servlet we used init method just to initialise the ServletConfig instance variable. Whenever you have to write an implementation of the Servlet, since we have to implement the getServletConfig() method we should have the instance variable and init method should do the initialisation. This should be there in any Servlet which you write. Can we do something by which we can create some base class instead of writing a blank implementation for destroy(), init() which is doing the same thing in all the Servlet and even the getServletInfo(). We can create some kind of a base class so that if we have to create any new servlet anytime then it is only service method which we need to override. That is the one which is doing job for us. How to process the request coming from the client and giving back the response. Thats the responsibility given to the service method and which is the main job. So thats something which is going to be different. So let us create our own base class.

 

Creating the BaseServlet class

 

We will create our BaseServlet, which can be used in any of our application. This base class will be abstract and only service method needs to be overridden and other methods will be the same. We will also write some utility method which will be useful. Utility methods will be those say if we have to use some method on ServletConfig, we will have to use getServletConfig() and then invoke those methods. Rather then that we can provide some methods in our BaseServlet itself.

 

The code listing for BaseServlet may look at given below:

package org.epgpathshala.servlet; import javax.servlet.*;

import java.io.*;

public abstract class BaseServlet implements Servlet, ServletConfig{ private ServletConfig config;

public final void init(ServletConfig cfg) { this.config = cfg;

init();

}

public void init() {}

public final ServletConfig getServletConfig() {}

public abstract void service(ServletRequest req, ServletResponse res) throws IOException, ServletException;

public final String getServletClass(){ return this.config.getServletClass();

}

public final Enumeration<String> getInitParameterNames()            

{ return this.config.getInitParameterNames();}

public final String getInitParameter(Strin name) { return this.config.getParameterName(name);}

public final ServletContext getServletContext() { return this.config.getServletContext();}

public final void log(String message) { getServletContext.log(message);}

public final void log(String message, Exception e) { getServletContext.log(message, e);}

public void destroy() {}

public String getServletInfo() { return “”;}

}

 

Recollect what we have in the servletConfig. ServletConfig provides four methods. Let us say, someone is interested in knowing the class name or interested in using those init parameters. So everywhere he has to use the code getServletConfig().getClassName(). or getServletConfig().getInitParameterNames() or getServletConfig().getServletContext() or getServletConfig().getInitParameter(). We can prevent those type of extra coding if we provide the methods of ServletConfig in our BaseServlet itself. ServletContext represents our web application. web container has a facility to maintain the logs and it has the facility that our servlet can also put the entry into the log. ServletContext has two log methods :

 

public void log(String message) – making the entry in the log with the time stamp and the message in the log.

 

Many times you might have some exception thrown and you might have written the try catch block and if you want to log the exceptions that occured, we have another log method, which has been overloaded and it can take two parameters. It can take message as well as an exception object.

 

public void log(String message, Throwable throwable)

 

The throwable object type is Throwable. So these are two methods of ServletContext. It will be convenient to have these two methods also as part of our BaseServlet. We will keep it as final.

 

We have declared few of the methods as final because we don’t want anybody to override and misuse the methods.

 

Here we have not written any implementation for the service method leaving it abstract for the subclasses to override and specify their implementation.

 

So the base class is going to be an abstract class. so we change the class to be abstract. Another method we will be overriding is the getServletInfo(). We override to return an empty string.

 

So from now onwards if we want to write any servlet we don’t have to write the implementation of Servlet interface and implement all the five methods.

 

Now lets have a new servlet and se how to write it. public class NewServlet extends BaseServlet {

 

public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

// code for servicing a request and giving a response

}

}

 

I wish it could be a part of an API so that each time I develop a new application I don’t need to put this class everywhere. Let see some similar thing in the API. We find GenericServlet in API.

 

Generic Servlet

 

So we coded a class similar to the GenericServlet but much improvised version of it. So, someone can write a new servlet by extending the GenericServlet class and then overriding the service method and overriding the init method without parameters but init with parameters in GenericServlet is not made final and so it has not done its job properly. It just mention that if you want to override this method you just do super.init(cfg) and don’t forget the initialization of the config which is just happening through the super class. So rather then doing it as a comment in the documentation it would have been a better idea if the method itself would have been final.

 

Similar things are applicable to the other methods which we made final. None of the methods are made final in the GenericServlet class. So, now we see two different ways of writing a servlet. One is you can write your own implementation of the Servlet interface by implementing each and every method or another better option is, you can write your class by extending a GenericServlet class. GenericServlet is from the API or you can use BaseServlet which we created instead of the GenericServlet. But you have to carry it in all the application because it is not the class in the API.

 

Servlet Request and Request Dispatcher

 

There are few other things that are remaining as far as the ServletRequest is concerned. We had seen some of the method of the ServletRequest. We don’t want one servlet doing all the processing as well as presentation part. Servlet here is acting as a single point where the request would come and being responsible for giving the response. It is the same object which has to be generating the response. One component doing processing of the whole request as well as giving response to it. We might like to distribute that job to more than one servlet. So, we got some options possible using some of the methods of ServletRequest. We have the methods in ServletRequest for extracting the parameters for reading the contents coming as part of a request. Whenever a request come to a servlet, it may do its own processing but as far as giving the response back to the container is concerned, by filling the buffer of the response with the content to be delivered and not giving back the response we can say.

 

We can have that job being done by the separate servlet. It is not only for the purpose of giving response their might be some other operations. So as part of processing the request come to one servlet, the servlet done its own job but then it says i have done my job let there be another servlet to do further more processing on this. A particular request which can be given to the servlet by the container. This servlet says i have done my job and let the request and response be forwarded to another servlet do its processing and give a response back or it may pass it on to someone else. So we have such a mechanism available here. The two important thing which can happen here is; Even while giving a response there is a servlet which started writing the response and while writing the response part of the response is filled into the content then it feels it is not my job to give the response, or after filling part of the response it feels, that let it be included to do some of the job by different servlet which will append some more things into the same buffer objects then I will continue filling more things into it. Such mechanisms are available to us.

 

Two things we saw; Sharing the same response object allowing different servlet to append more content what I have already written. Another thing is I am not going to write any content let there be someone else who take care of the content part and i am forwarding it further.So we have two things: One is including content or forwarding the request to someone else to take care of it. So let see what the object available for this.

 

In the servlet API we have the interface called RequestDispatcher and it is the ServletRequest which can give us the object of RequestDispatcher. One is use ServletRequest to get the RequestDispatcher.

 

Another way of creating RequestDispatcher which is by using the ServletContext object. In both the cases we would be interested in forwarding our request or including something from a different resource. So we have resource on our server side. It is normally a client who is accessing the resource but now is the time where on the server side itself within the same application some other resource is to be used by servlet. So, for that we use the RequestDispatcher. In the ServletContext we have additional method called getRequestDispatcher

 

public RequestDispatcher getRequestDispatcher(String URL)

 

and you need to start this url with the “/”. The “/” here matches the root of the application. Here you can use it to access any resource which is part of the server side, it includes even the WEB-INF. Even in the WEB-INF if some file is available I can use it as a resource and try to look forward the content. forward and include are the acitivities done by the RequestDispatcher. One way to create RequestDispatcher on ServletContext use the method called getRequestDispatcher(). We have another method on the ServletContext which says getNamedDispatcher

 

public RequestDispatcher getNamedDispatcher(Stirng nameofresource)

 

and returns the object of RequestDispatcher. So, in ServletContext we have two mwthods:

 

public RequestDispatcher getRequestDispatcher(String url)

public RequestDispatcher getNamedDispatcher(String resourcename)

 

In getNamedDispatcher we are not giving the resource url there is no resource url, the string here would use the name, a servlet-name. In web.xml we create the servlet object the servlet are resources, they have service method they are capable of servicing. So if you want to create RequestDispatcher which maps to the servlet whose entry we have. The servlet-name whichever is used here that can be used in this method called getNamedDispatcher.

 

We also have a method in ServletRequest called getRequestDispatcher

 

public RequestDispatcher getRequestDispatcher(String url)

 

but the string we use here does not start with the “/”, and the string we used in ServletContext method it always start with the “/”. The string which we are specifying if relate to the request, we have request object created and it was created due to particular url. So this is the resource which is relative to the current request by giving some path to current request. I have done my part and let the response be taken care by someone else so one option is forward. RequestDispatcher has two methods:

 

public void forward(ServletRequest request, ServletResponse response)

 

it reset and it will not be done if the response is already comitted because it has to reset first then request dispatcher will map to the particular resource and then it will fill the response. The responsibility goes to the next one. if you do forward then you should immediately return from it and should not do any further processing on it.

 

public void include(ServletRequest request, ServletResponse resposne)

 

I will fill certain things and then i want other servlet to append the buffer which will be done by include.

 

In both the methods whatever request response object we are getting we simply pass it on. We did some processing and asking someone to add response to it what will be needed here is the ability to share some objects, Share some objects between the two servlets. There is something common between them is we are using the same request object. So the other servlet gets the same request object so ServletRequest has the ability to store objects.

 

Sharing objects using attributes

 

ServletRequest is a place which can be used for sharing the objects. give a name and store the objects. We have set of four methods here:

 

public void setAttribute(String name, Object o) – assigning name and storing the objects

public Object getAttribute(String name) – return object

public Enumeration<String> getAttributeNames() – returns Enumeration of string.

public void removeAttribute(String name)

So this is common here which will be available to other servlet for further processing. This is how the objects are shared through request. We have something common throughout the application i.e. ServletContext object. The same set of four methods are also availabe in ServletContext.

 

public void setAttribute(String name, Object o) – assigning name and storing the objects

public Object getAttribute(String name) – return object

public Enumeration<String> getAttributeNames() – returns Enumeration of string.

public void removeAttribute(String name)

you can view video on More Servlet API

Suggested Reading:

  1. Core Servlets and Java Server Pages Volume1 by Marty Hall & Larry Brown, Second Edition, Pearson Education.
  2. Inside Servlets by Dustin R Callaway, Pearson Education.
  3. Java Server Programming for Professionals by Ivan Bayross, Sharanam Shah, Cynhthia Bayross and Vaishali Shah Shroff Publishers and Distributros.
  4. http://download.oracle.com/otndocs/jcp/servlet-3.0-fr-oth-JSpec/