17 Basic Servlet API

Pravin Jain

epgp books

 

Introduction

 

In this module we will look at the Servlet interface as a whole and the corresponding interface which are used from Servlet, which are init method in the servlet life cycle, so we have the ServletConfig object being injected in the Servlet object. So, ServletConfig methods would be explored. ServletConfig makes available to us the ServletContext object. ServletContext methods are useful giving us some information in web.xml file. So how to fetch the information from web.xml, and we will also explore ServletRequest and ServletResponse object. And finally we will create our first Servlet which will be used for giving very simple response called “HelloWorld”. So, we would like to create some HTML output which will generate a “Hello world”.

 

Quick Review of Servlet life cycle.

 

Three basic methods in servlet life cycle:

 

public void init(ServletConfig cfg)

 

As soon as the web container starts, it identifies the applications. Per application it creates a ServletContext Object. At the time of creating ServletContext object it is going through web.xml file and it get the display name from web.xml, which is going to be available through ServletContext object because this is one per application.

 

Servlet Context

 

The ServletContext is nothing but your web application. So the display name can be known using the getServletContextName() method.

 

public String getServletContextName()

public Enumeration<String> getInitParameterNames()

 

it is used to get the context-param name which is set by the one who has created web.xml to initialize the parameter. If you have got five different parameters then all the parameter names will be available through this Enumeration<String>.

 

public String getInitParameter(String name)

 

Once you know the name of the parameters you can fetch the value of the parameter by using this method. these values are set on the ServletContext.

 

Now it will look for the entries of <servlet>. For each servlet class it creates an object. But before it creates the object of the servlet class it creates an object of ServletConfig. We have got an another interface called ServletConfig. ServletConfig is specific to the Servlet. if we have got five different entries for the <servlet> it has to create five different servlet objects, corresponding to this each <servlet> entries it would be also creating the ServletConfig and each ServletConfig will have ServletContext available to them.

 

Servlet Config

 

ServletConfig has all the information related to the ServletContext and Servlet.

 

ServletConfig methods:

  1. public ServletContext getServletContext() – returns the ServletContext
  2. public String getServletName() – returns the name of the servlet entry.
  3. public Enumeration<String> getInitParameterNames() – returns the enumeration of string.
  4. public String getInitParameter(String name) – returns the value of the paratmeter.

 

Then life of the Servlet starts. It begins with the method init. During this init the object of ServletConfig is injected into the Servlet object. ServletContext and ServletConfig are the objects coming from the container. These are the interfaces implemented by the server vendor and not by the developer. The web developer is creating the component called Servlet. in init ServletConfig is made available to the Servlet. ServletContext and ServletConfig are made available to the web developer.

 

init is able to give web developer access to the web container. It is the ServletContext through which the developer is getting access to the entire application. Once the initialization of all the <servlet> entries is done and ServletContext and ServletConfig all of them is getting initialized. Once all the initialization, the one mentioned in deployment descriptor (web.xml file) and other components is created it is then that too corresponding to all the web applications which are on the server it is then that the container now becomes ready to start accepting request from the client.

 

So we have a huge start up phase and it is during this start up phase of the web container the init method is getting invoked and all the servlets are ready with them and initialized. Once the container is ready and any client using the url hits the container, the container looks up for the <url-pattern> in the <servlet-mapping> entry. If it matches any of the <url-pattern> it is able to identify the servlet. After identifying the servlet it will be able to invoke the life-cycle method of the servlet called service.

 

The service method requires the ServletRequest and ServletResponse object as a parameter. These are not the objects of the developer these are the objects of the server vendor. The request arrives using the http protocol. It is the container who knows the http protocol and not the application developer who is having no knowledge of the http protocol. Container is the one who is able to understand the request coming to any of the protocol(Http, SIP etc…). So whenever the request arrives two things should be done by the container:

 

The container has to create two objects here :

 

–  ServletRequest object

–  ServletResponse object

 

Considering the http protocol being used here, we would have a ServletRequest object which would be created. It would have nothing but the information which has come as the part of the http protocol. All that information would be encapsulated in the ServletRequest.

 

Servlet Response

 

The other object i.e. ServletResponse object get created by allocating a buffer. The container is allocating a blank buffer, encapsulating it in an object of ServletResponse, these two objects are then going to be made available to the Servlet. The web developer is not going to use http protocol to send his response back but he has to fill in the content into the blank buffer. Whatever content he puts into the buffer it is the containers responsibility to see that the content in the buffer, once the service method is over, to send the content back to the client.

 

The content is generated by the servlet and put into a buffer and sending it back to the client is the responsibility of the container and servlet has no role there. The servlet has nothing to do with how http works. Before sending the content back, the developer may like to see the content received from the client if any, and for that we have the ServletRequest object.. To fill in the buffer we have methods in the ServletResponse object, and to fetch the information from the request, we have methods in the ServletRequest object.

 

ServletResponse methods as follows:

public int getBufferSize()

public void setBufferSize(int bufsize)

 

These are the two methods to set and get the buffer size. Before putting the content into the buffer we would like to specify the type of the content and set the type of the content. So for that we have the method:

 

public String getContentType()

public void setContentType(String mimeType) most commonly set to “text/html” example:

response.setContentType(“text/html”);

 

If you are interested you can even specify the length there but not compulsory. We have some mechanism to fill in the buffer with the content. What happens in case the buffer is full. It is not an error if you exceed your buffer size but the partial content will be sent to the client. We have various settings in the ServletResponse like the content-length, character-encoding, like I am sending the text content, so what is the character encoding I am using here like UTF-8 etc.. So we have methods for character encoding:

 

public void setCharacterEncoding(String csn) public String getCharacterEncoding()

 

After filling part of the buffer I may feel, I made some mistake and I would like to change the content type and few other things. These are the meta information made available in the ServletResponse about the content. If the buffer is not full you are free to make these changes like change in character encoding, content type etc. But if the buffer is full then the metadata information has been moved out it has already been sent to client. So the client is now aware that the content coming is so and so. like html and not the xml/pdf/image and this is how it commits to the client by sending the information about the content to the client. In such a stage the state of the response has changes, the response is set to the committed state. once a response is committed we cannot make any changes to metadata information like content type, character encoding etc. So, if th buffer is full the content will move out and no more changes will be allowed. We do have the method to check that:

 

public boolean isCommitted() in the servlet response- returns boolean.

public void flushBuffer() – the response will be committed in this case.

public void reset() – will reset the buffer content as well as metadata information will also be reset.

 

public void resetBuffer() – will reset only buffer.reset and resetBuffer will not work if the response is already committed. We want to set the content type and the content say binary content or it is a text content. If it is a binary content it will be more appropriate to have an OutputStream to write the binary content into the buffer. You will have two kinds of stream to write. A binary stream or the text stream. You can have the binary stream with the help of method called getOutputStream() – return us a servlet output stream which is the subclass of the OutputStream or you can use a method called getWriter() – return PrintWriter.

 

public ServletOutputStream getOutputStream()

public PrintWriter getWriter()

 

So, according to the content type you need to select the stream.

 

Servlet Request

 

As part of a request we might get some parameters say for example some form has been submitted then we have <input> tag in the html. In <input> tag we have a name, so that name of an input tag and the form is submitted that is coming as an request to the server. So as part of ServletRequest, a ServletRequest may have parameter name and the corresponding value. So if there is an html form being filled out, the name becomes the parameter name and the value corresponding to the parameter name is the parameter value.

 

So any number of parameter values can be there.

 

In ServletRequest we have methods for fetching those parameters.

 

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

public String[] getParameterValues(String pname) – returns an array of string, it can have multiple values.

 

The name of parameter can be same with multiple values. For single value we have the method:

 

public String getParameterValue(String pname) – returns the single value and it will give you the first value.

public Map<String, String[]> getParameterMap() – returns the mapping of parameter name and the corresponding values in the string array.

 

ServletRequest can have even content coming from it. let us say, you are having an attachment that means client is sending attachment to the server. We have method to fetch the content submitted by the client to the server and also the type of the content by using method:

 

public String getContentType()

 

and  to know the length of the content we have method:

 

public int getContentLength()

 

If you want to read the content then we can use the stream. If it is a binary content we can make use of ServletInputStream, which we can get using method

 

public ServletInputStream getInputStream() and we can use the method:

public BufferedReader getReader()

 

which will return the object of the BufferedReader. BufferedReader has the method called readLine() which reads the content line by line. ServletRequest will also have the information like what are preferences of the user in terms of the locale he likes using the method called getLocale()

 

public Locale getLocale()

 

to give us the language and country preference. We have seen only three methods of the Servlet called init(), service() and destroy().

 

In Servlet’s init method, whatever the ServletConfig is injected, there is a method called getServletConfig()

 

public ServletConfig getServletConfig()

 

to know the ServletConfig made available to the Servlet. We keep one instance variable which is initialised in the init method. Servlet has also another method:

 

public String getServletInfo() – implement it to return some copyright message. So servlet has five methods :

public void init(ServletConfig cfg) throws ServletException public void destroy()

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

 

ServletException

public ServletConfig getServletConfig() public String getServletInfo()

 

As a first exercise:

 

We will write a servlet and deploy it to see what happens. we will give fix response here. Let us define this servlet class by the name HelloServlet under the package org.epgpathshala.

 

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

import java.io.servlet.*;

public class HelloServlet implements Servlet {

private ServletConfig config;

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

}

public void destroy() {

}

public ServletConfig getServletConfig() { return this.config;

}

public String getServletInfo() {

return ” HelloServlet (C)opuright epgpathshala”;

}

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

res.setContentType(“text/html”); PrintWriter out = res.getWriter();

out.println(“<html><head><title>Hello  Servlet</title></head>”); out.println(“<body><h1>Hello World!</h1></body></html>”);

}

}

 

Once we have finished implementing the Servlet, what we need to do here is compile this and put this under the classes folder of our web application folder. While compiling give -d to specify the classes folder.

 

If we call this application as sample we will have a folder called sample within which we will have a WEB-INF folder, where we have a classes folder. So within classes package folder will be created and the classes will be available. We now need to create the web.xml file. The content of web.xml can be as given below:

 

<web-app>

<display-name>Sample</display-name>

<servlet>

<servlet-name>Hello</servlet-name>

<servlet-class>org.epgPathshala.HelloServlet</servlet-class>

</servlet>

<servlet>

<servlet-name>Hi</servlet-name>

<servlet-class>org.epgPathshala.HelloServlet            </servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Hello</servlet-name>

<url-pattern>/Hello</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>Hi</servlet-name>

<url-pattern>/hi/*</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>Hello</servlet-name>

<url-pattern>*.hello</url-pattern>

</servlet-mapping>

</web-app>

 

now deploying this sample application. Within tomcat there is a folder called webapps and put it into it and restart the tomcat. Now, from a browser try the following Url.

 

http://localhost:8080/sample/Hello

or http://localhost:8080/sample/hi/anypath or

http://localhost:8080/sample/somepath.hello

you can view video on Basic 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/