What is Servlet ?
Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
What is web application?
A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request.
CGI(Commmon Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.
Disadvantages of CGI
There are many problems in CGI technology:
- If number of clients increases, it takes more time for sending response.
- For each request, it starts a process and Web server is limited to start processes.
- It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet
There are many advantages of servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:
- better performance: because it creates a thread for each request not process.
- Portability: because it uses java language.
- Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc.
- Secure: because it uses java language..
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
Servlets Tasks:
Servlets perform the following major tasks:
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.
Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.
Servlet Terminology
There are some key points that must be known by the servlet programmer like server, container, get request, post request etc. Let's first discuss these points before starting the servlet technology.
The basic terminology used in servlet are given below:
- HTTP
- HTTP Request Types
- Difference between Get and Post method
- Container
- Server and Difference between web server and application server
- Content Type
- Introduction of XML
- Deployment
HTTP (Hyper Text Transfer Protocol)
- Http is the protocol that allows web servers and browsers to exchange data over the web.
- It is a request response protocol.
- Http uses reliable TCP connections bydefault on TCP port 80.
- It is stateless means each request is considered as the new request. In other words, server doesn't recognize the user bydefault.
Http Request Methods
Every request has a header that tells the status of the client. There are many request methods. Get and Post requests are mostly used.
The http request methods are:
- GET
- POST
- HEAD
- PUT
- DELETE
- OPTIONS
- TRACE
HTTP Request | Description |
---|---|
GET | Asks to get the resource at the requested URL. |
POST | Asks the server to accept the body info attached. It is like GET request with extra info sent with the request. |
HEAD | Asks for only the header part of whatever a GET would return. Just like GET but with no body. |
TRACE | Asks for the loopback of the request message, for testing or troubleshooting. |
PUT | Says to put the enclosed info (the body) at the requested URL. |
DELETE | Says to delete the resource at the requested URL. |
OPTIONS | Asks for a list of the HTTP methods to which the thing at the request URL can respond |
What is the difference between Get and Post?
There are many differences between the Get and Post request. Let's see these differences:
GET | POST |
---|---|
1) In case of Get request, only limited amount of data can be sent because data is sent in header. | In case of post request, large amount of data can be sent because data is sent in body. |
2) Get request is not secured because data is exposed in URL bar. | Post request is secured because data is not exposed in URL bar. |
3) Get request can be bookmarked | Post request cannot be bookmarked |
4) Get request is idempotent. It means second request will be ignored until response of first request is delivered. | Post request is non-idempotent |
5) Get request is more efficient and used more than Post | Post request is less efficient and used less than get. |
Anatomy of Get Request
As we know that data is sent in request header in case of get request. It is the default request type. Let's see what informations are sent to the server.
Anatomy of Post Request
As we know, in case of post request original data is sent in message body. Let's see how informations are passed to the server in case of post request.
Container
It provides runtime environment for JavaEE (j2ee) applications.
It performs many operations that are given below:
- Life Cycle Management
- Multithreaded support
- Object Pooling
- Security etc.
Server
It is a running program or software that provides services.
There are two types of servers:
- Web Server
- Application Server
Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB.
Example of Web Servers are: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc.
Example of Application Servers are:
- JBoss Open-source server from JBoss community.
- Glassfish provided by Sun Microsystem. Now acquired by Oracle.
- Weblogic provided by Oracle. It more secured.
- Websphere provided by IBM.
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP header that provides the description about what are you sending to the browser.
There are many content types:
- text/html
- text/plain
- application/msword
- application/vnd.ms-excel
- application/jar
- application/pdf
- application/octet-stream
- application/x-zip
- images/jpeg
- video/quicktime etc.
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet
The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.
The init() method :
The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException { // Initialization code... }
The service() method :
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ }
The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
The destroy() method :
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:
public void destroy() { // Finalization code... }
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
- Servlet
- ServletRequest
- ServletResponse
- RequestDispatcher
- ServletConfig
- ServletContext
- SingleThreadModel
- Filter
- FilterConfig
- FilterChain
- ServletRequestListener
- ServletRequestAttributeListener
- ServletContextListener
- ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
- GenericServlet
- ServletInputStream
- ServletOutputStream
- ServletRequestWrapper
- ServletResponseWrapper
- ServletRequestEvent
- ServletContextEvent
- ServletRequestAttributeEvent
- ServletContextAttributeEvent
- ServletException
- UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
- HttpServletRequest
- HttpServletResponse
- HttpSession
- HttpSessionListener
- HttpSessionAttributeListener
- HttpSessionBindingListener
- HttpSessionActivationListener
- HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
- HttpServlet
- Cookie
- HttpServletRequestWrapper
- HttpServletResponseWrapper
- HttpSessionEvent
- HttpSessionBindingEvent
- HttpUtils (deprecated now)
Creating Servlet Example in Eclipse
Eclipse is an open-source ide for developing JavaSE and JavaEE (J2EE) applications. You can download the eclipse ide from the eclipse website http://www.eclipse.org/downloads/.
You need to download the eclipse ide for JavaEE developers.
Creating servlet example in eclipse ide, saves a lot of work to be done. It is easy and simple to create a servlet example. Let's see the steps, you need to follow to create the first servlet example.
- Create a Dynamic web project
- create a servlet
- add servlet-api.jar file
- Run the servlet
1) Create the dynamic web project:
For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic web project -> write your project name e.g. first -> Finish.
2) Create the servlet in eclipse IDE:
For creating a servlet, explore the project by clicking the + icon -> explore the Java Resources -> right click on src -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish.
3) add jar file in eclipse IDE:
For adding a jar file, right click on your project -> Build Path -> Configure Build Path -> click on Libraries tab in Java Build Path -> click on Add External JARs button -> select the servlet-api.jar file under tomcat/lib -> ok. |
Now servlet has been created, Let's write the first servlet code. |
4) Start the server and deploy the project:
For starting the server and deploying the project in one step, Right click on your project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish.
Now tomcat server has been started and project is deployed. To access the servlet write the url pattern name in the URL bar of the browser. In this case Hello then enter.
How to configure tomcat server in Eclipse ? (One time Requirement)
If you are using Eclipse IDE first time, you need to configure the tomcat server First.
For configuring the tomcat server in eclipse IDE, click on servers tab at the bottom side of the IDE -> right click on blank area -> New -> Servers -> choose tomcat then its version -> next -> click on Browse button -> select the apache tomcat root folder previous to bin -> next -> addAll -> Finish.
Now tomcat7 server has been configured in eclipse IDE. |
Servlet Interface
Servlet interface provides common behaviour to all the servlets.
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container.
Method | Description |
---|---|
public void init(ServletConfig config) | initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. |
public void service(ServletRequest request,ServletResponse response) | provides response for the incoming request. It is invoked at each request by the web container. |
public void destroy() | is invoked only once and indicates that servlet is being destroyed. |
public ServletConfig getServletConfig() | returns the object of ServletConfig. |
public String getServletInfo() | returns information about servlet such as writer, copyright, version etc. |
Servlet Example by implementing Servlet interface
Let's see the simple example of servlet by implementing the servlet interface.
It will be better if you learn it after visiting steps to create a servlet.
welcome-file-list in web.xml
The welcome-file-list element of web-app, is used to define a list of welcome files. Its sub element is welcome-file that is used to define the welcome file.
A welcome file is the file that is invoked automatically by the server, if you don't specify any file name.
By default server looks for the welcome file in following order:
- welcome-file-list in web.xml
- index.html
- index.htm
- index.jsp
If none of these files are found, server renders 404 error.
If you have specified welcome-file in web.xml, and all the files index.html, index.htm and index.jsp exists, priority goes to welcome-file.
If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file then index.htm and at last index.jsp file.
Let's see the web.xml file that defines the welcome files.
Now, home.html and default.html will be the welcome files.
If you have the welcome file, you can directory invoke the project as given below:
As you can see, we have not specified any file name after the project.
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.
Difference between forward() and sendRedirect() method
There are many differences between the forward() method of RequestDispatcher and sendRedirect() method of HttpServletResponse interface. They are given below:
forward() method | sendRedirect() method |
---|---|
The forward() method works at server side. | The sendRedirect() method works at client side. |
It sends the same request and response objects to another servlet. | It always sends a new request. |
It can work within the server only. | It can be used within and outside the server. |
Example: request.getRequestDispacher("servlet2").forward(request,response); | Example: response.sendRedirect("servlet2"); |
Syntax of sendRedirect() method
Example of sendRedirect() method
Full example of sendRedirect method in servlet
In this example, we are redirecting the request to the google server. Notice that sendRedirect method works at client side, that is why we can our request to anywhere. We can send our request within and outside the server. |
Creating custom google search using sendRedirect
In this example, we are using sendRedirect method to send request to google server with the request data.
Output
ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the web.xml file.
Methods of ServletConfig interface
- public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
- public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
- public String getServletName():Returns the name of the servlet.
- public ServletContext getServletContext():Returns an object of ServletContext.
How to get the object of ServletConfig
- getServletConfig() method of Servlet interface returns the object of ServletConfig.
Syntax of getServletConfig() method
Example of getServletConfig() method
Syntax to provide the initialization parameter for a servlet
The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.
Example of ServletConfig to get initialization parameter
In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet.
DemoServlet.java
web.xml
Example of ServletConfig to get all the initialization parameters
In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.
DemoServlet.java
web.xml
An object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc.
Methods of ServletRequest interface
There are many methods defined in the ServletRequest interface. Some of them are as follows:
Method | Description |
---|---|
public String getParameter(String name) | is used to obtain the value of a parameter by name. |
public String[] getParameterValues(String name) | returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box. |
java.util.Enumeration getParameterNames() | returns an enumeration of all of the request parameter names. |
public int getContentLength() | Returns the size of the request entity data, or -1 if not known. |
public String getCharacterEncoding() | Returns the character set encoding for the input of this request. |
public String getContentType() | Returns the Internet Media Type of the request entity data, or null if not known. |
public ServletInputStream getInputStream() throws IOException | Returns an input stream for reading binary data in the request body. |
public abstract String getServerName() | Returns the host name of the server that received the request. |
public int getServerPort() | Returns the port number on which this request was received. |
Example of ServletRequest to display the name of the user
In this example, we are displaying the name of the user in the servlet. For this purpose, we have used the getParameter method that returns the value for the given request parameter name.
index.html
DemoServ.java
ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus it removes maintenance problem.
Usage of ServletContext Interface
There can be a lot of usage of ServletContext object. Some of them are as follows:
- The object of ServletContext provides an interface between the container and servlet.
- The ServletContext object can be used to get configuration information from the web.xml file.
- The ServletContext object can be used to set, get or remove attribute from the web.xml file.
- The ServletContext object can be used to provide inter-application communication.
Commonly used methods of ServletContext interface
There is given some commonly used methods of ServletContext interface.
|
How to get the object of ServletContext interface
- getServletContext() method of ServletConfig interface returns the object of ServletContext.
- getServletContext() method of GenericServlet class returns the object of ServletContext.
Syntax of getServletContext() method
Example of getServletContext() method
Syntax to provide the initialization parameter in Context scope
The context-param element, subelement of web-app, is used to define the initialization parameter in the application scope. The param-name and param-value are the sub-elements of the context-param. The param-name element defines parameter name and and param-value defines its value. |
Example of ServletContext to get the initialization parameter
In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don't need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let's see the simple example: |
DemoServlet.java
Example of ServletContext to get all the initialization parameters
In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class. |
DemoServlet.java
Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one of the following scopes:
- request scope
- session scope
- application scope
The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.
Attribute specific methods of ServletRequest, HttpSession and ServletContext interface
There are following 4 attribute specific methods. They are as follows:
|
Example of ServletContext to set and get attribute
In this example, we are setting the attribute in the application scope and getting that value from another servlet. |
DemoServlet1.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet1 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); context.setAttribute("company","IBM"); out.println("Welcome to first servlet"); out.println("<a href='servlet2'>visit</a>"); out.close(); }catch(Exception e){out.println(e);} }}
DemoServlet2.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet2 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); String n=(String)context.getAttribute("company"); out.println("Welcome to "+n); out.close(); }catch(Exception e){out.println(e);} }}
web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>DemoServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>DemoServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
Difference between ServletConfig and ServletContext
The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole web application. |
The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They are:
- public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
- public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client. |
How to get the object of RequestDispatcher
The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax:
Syntax of getRequestDispatcher method
Example of using getRequestDispatcher method
Example of RequestDispatcher interface
In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are cheking for hardcoded information. But you can check it to the database also that we will see in the development chapter. In this example, we have created following files:
- index.html file: for getting input from the user.
- Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet.
- WelcomeServlet.java file: a servlet class for displaying the welcome message.
- web.xml file: a deployment descriptor file that contains the information about the servlet.
index.html
Login.java
WelcomeServlet.java
web.xml
load on startup in web.xml
The load-on-startup element of web-app loads the servlet at the time of deployment or server start if value is positive. It is also known as pre initialization of servlet.
You can pass positive and negative value for the servlet.
Advantage of load-on-startup element
As you know well, servlet is loaded at first request. That means it consumes more time at first request. If you specify the load-on-startup in web.xml, servlet will be loaded at project deployment time or server start. So, it will take less time for responding to first request.
Passing positive value
If you pass the positive value, the lower integer value servlet will be loaded before the higher integer value servlet. In other words, container loads the servlets in ascending integer value. The 0 value will be loaded first then 1, 2, 3 and so on.
Let's try to understand it by the example given below:
There are defined 2 servlets, both servlets will be loaded at the time of project deployment or server start. But, servlet1 will be loaded first then servlet2.
Passing negative value
If you pass the negative value, servlet will be loaded at request time, at first request.
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementaion of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
- public void init(ServletConfig config) is used to initialize the servlet.
- public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.
- public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.
- public ServletConfig getServletConfig() returns the object of ServletConfig.
- public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
- public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)
- public ServletContext getServletContext() returns the object of ServletContext.
- public String getInitParameter(String name) returns the parameter value for the given parameter name.
- public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.
- public String getServletName() returns the name of the servlet object.
- public void log(String msg) writes the given message in the servlet log file.
- public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace.
Servlet Example by inheriting the GenericServlet class
Let's see the simple example of servlet by inheriting the GenericServlet class.
It will be better if you learn it after visiting steps to create a servlet.
How Servlet works?
It is important to learn how servlet works for understanding the servlet well. Here, we are going to get the internal detail about the first servlet program.
The server checks if the servlet is requested for the first time.
If yes, web container does the following tasks:
- loads the servlet class.
- instantiates the servlet class.
- calls the init method passing the ServletConfig object
else
- calls the service method passing request and response objects
The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project.
How web container handles the servlet request?
The web container is responsible to handle the request. Let's see how it handles the request.
- maps the request with the servlet in the web.xml file.
- creates request and response objects for this request
- calls the service method on the thread
- The public service method internally calls the protected service method
- The protected service method calls the doGet method depending on the type of request.
- The doGet method generates the response and it is passed to the client.
- After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.
What is written inside the public service method?
The public service method converts the ServletRequest object into the HttpServletRequest type and ServletResponse object into the HttpServletResponse type. Then, calls the service method passing these objects. Let's see the internal code:
What is written inside the protected service method?
The protected service method checks the type of request, if request type is get, it calls doGet method, if request type is post, it calls doPost method, so on. Let's see the internal code:
When a browser requests for a web page, it sends lot of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very frequently in web programming:
Header | Description |
---|---|
Accept | This header specifies the MIME types that the browser or other clients can handle. Values of image/png or image/jpeg are the two most common possibilities. |
Accept-Charset | This header specifies the character sets the browser can use to display the information. For example ISO-8859-1. |
Accept-Encoding | This header specifies the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities. |
Accept-Language | This header specifies the client's preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc. |
Authorization | This header is used by clients to identify themselves when accessing password-protected Web pages. |
Connection | This header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used |
Content-Length | This header is applicable only to POST requests and gives the size of the POST data in bytes. |
Cookie | This header returns cookies to servers that previously sent them to the browser. |
Host | This header specifies the host and port as given in the original URL. |
If-Modified-Since | This header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available. |
If-Unmodified-Since | This header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date. |
Referer | This header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referer header when the browser requests Web page 2. |
User-Agent | This header identifies the browser or other client making the request and can be used to return different content to different types of browsers. |
Methods to read HTTP Header:
There are following methods which can be used to read HTTP header in your servlet program. These methods are available with HttpServletRequest object.
S.N. | Method & Description |
---|---|
1 | Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request. |
2 | Enumeration getAttributeNames() Returns an Enumeration containing the names of the attributes available to this request. |
3 | Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains. |
4 | Enumeration getParameterNames() Returns an Enumeration of String objects containing the names of the parameters contained in this request. |
5 | HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. |
6 | HttpSession getSession(boolean create) Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. |
7 | Locale getLocale() Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. |
8 | Object getAttribute(String name) Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. |
9 | ServletInputStream getInputStream() Retrieves the body of the request as binary data using a ServletInputStream. |
10 | String getAuthType() Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or "SSL," or null if the JSP was not protected. |
11 | String getCharacterEncoding() Returns the name of the character encoding used in the body of this request. |
12 | String getContentType() Returns the MIME type of the body of the request, or null if the type is not known. |
13 | String getContextPath() Returns the portion of the request URI that indicates the context of the request. |
14 | String getHeader(String name) Returns the value of the specified request header as a String. |
15 | String getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. |
16 | String getParameter(String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. |
17 | String getPathInfo() Returns any extra path information associated with the URL the client sent when it made this request. |
18 | String getProtocol() Returns the name and version of the protocol the request. |
19 | String getQueryString() Returns the query string that is contained in the request URL after the path. |
20 | String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent the request. |
21 | String getRemoteHost() Returns the fully qualified name of the client that sent the request. |
22 | String getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. |
23 | String getRequestURI() Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. |
24 | String getRequestedSessionId() Returns the session ID specified by the client. |
25 | String getServletPath() Returns the part of this request's URL that calls the JSP. |
26 | String[] getParameterValues(String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. |
27 | boolean isSecure() Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS. |
28 | int getContentLength() Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. |
29 | int getIntHeader(String name) Returns the value of the specified request header as an int. |
30 | int getServerPort() Returns the port number on which this request was received. |
HTTP Header Request Example:
Following is the example which uses getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class DisplayHeader extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "HTTP Header Request Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<table width=\"100%\" border=\"1\" align=\"center\">\n" + "<tr bgcolor=\"#949494\">\n" + "<th>Header Name</th><th>Header Value(s)</th>\n"+ "</tr>\n"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String paramName = (String)headerNames.nextElement(); out.print("<tr><td>" + paramName + "</td>\n"); String paramValue = request.getHeader(paramName); out.println("<td> " + paramValue + "</td></tr>\n"); } out.println("</table>\n</body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Now calling the above servlet would generate following result:
HTTP Header Request Example
Header Name | Header Value(s) |
---|---|
accept | */* |
accept-language | en-us |
user-agent | Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8) |
accept-encoding | gzip, deflate |
host | localhost:8080 |
connection | Keep-Alive |
cache-control | no-cache |
Servlets - Server HTTP Response
As discussed in previous chapter, when a Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document. A typical response looks like this:
HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser from web server side and you would use them very frequently in web programming:
Header | Description |
---|---|
Allow | This header specifies the request methods (GET, POST, etc.) that the server supports. |
Cache-Control | This header specifies the circumstances in which the response document can safely be cached. It can have values public, private or no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (nonshared) caches and no-cache means document should never be cached. |
Connection | This header instructs the browser whether to use persistent in HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keep-alive means using persistent connections. |
Content-Disposition | This header lets you request that the browser ask the user to save the response to disk in a file of the given name. |
Content-Encoding | This header specifies the way in which the page was encoded during transmission. |
Content-Language | This header signifies the language in which the document is written. For example en, en-us, ru, etc. |
Content-Length | This header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection. |
Content-Type | This header gives the MIME (Multipurpose Internet Mail Extension) type of the response document. |
Expires | This header specifies the time at which the content should be considered out-of-date and thus no longer be cached. |
Last-Modified | This header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modified-Since request header in later requests. |
Location | This header should be included with all responses that have a status code in the 300s. This notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document. |
Refresh | This header specifies how soon the browser should ask for an updated page. You can specify time in number of seconds after which a page would be refreshed. |
Retry-After | This header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request. |
Set-Cookie | This header specifies a cookie associated with the page. |
Methods to Set HTTP Response Header:
There are following methods which can be used to set HTTP response header in your servlet program. These methods are available with HttpServletResponse object.
S.N. | Method & Description |
---|---|
1 | String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. |
2 | String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. |
3 | boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set. |
4 | boolean isCommitted()
Returns a boolean indicating if the response has been committed. |
5 | void addCookie(Cookie cookie)
Adds the specified cookie to the response. |
6 | void addDateHeader(String name, long date)
Adds a response header with the given name and date-value. |
7 | void addHeader(String name, String value)
Adds a response header with the given name and value. |
8 | void addIntHeader(String name, int value)
Adds a response header with the given name and integer value. |
9 | void flushBuffer()
Forces any content in the buffer to be written to the client. |
10 | void reset()
Clears any data that exists in the buffer as well as the status code and headers. |
11 | void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code. |
12 | void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer. |
13 | void sendError(int sc, String msg)
Sends an error response to the client using the specified status. |
14 | void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL. |
15 | void setBufferSize(int size)
Sets the preferred buffer size for the body of the response. |
16 | void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8. |
17 | void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header. |
18 | void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet. |
19 | void setDateHeader(String name, long date)
Sets a response header with the given name and date-value. |
20 | void setHeader(String name, String value)
Sets a response header with the given name and value. |
21 | void setIntHeader(String name, int value)
Sets a response header with the given name and integer value. |
22 | void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet. |
23 | void setStatus(int sc)
Sets the status code for this response. |
HTTP Header Response Example:
You already have seen setContentType() method working in previous examples and following example would also use same method, additionally we would use setIntHeader() method to set Refresh header.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class Refresh extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Set response content type response.setContentType("text/html"); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriter out = response.getWriter(); String title = "Auto Refresh Header Setting"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p>Current Time is: " + CT + "</p>\n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Now calling the above servlet would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result:
Servlets - Http Status Codes
The format of the HTTP request and HTTP response messages are similar and will have following structure:
An initial status line + CRLF ( Carriage Return + Line Feed ie. New Line )
Zero or more header lines + CRLF
A blank line ie. a CRLF
An optioanl message body like file, query data or query output.
For example, a server response header looks as follows:
HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example).
Following is a list of HTTP status codes and associated messages that might be returned from the Web Server:
Code: | Message: | Description: |
---|---|---|
100 | Continue | Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request |
101 | Switching Protocols | The server switches protocol. |
200 | OK | The request is OK |
201 | Created | The request is complete, and a new resource is created |
202 | Accepted | The request is accepted for processing, but the processing is not complete. |
203 | Non-authoritative Information | |
204 | No Content | |
205 | Reset Content | |
206 | Partial Content | |
300 | Multiple Choices | A link list. The user can select a link and go to that location. Maximum five addresses |
301 | Moved Permanently | The requested page has moved to a new url |
302 | Found | The requested page has moved temporarily to a new url |
303 | See Other | The requested page can be found under a different url |
304 | Not Modified | |
305 | Use Proxy | |
306 | Unused | This code was used in a previous version. It is no longer used, but the code is reserved. |
307 | Temporary Redirect | The requested page has moved temporarily to a new url. |
400 | Bad Request | The server did not understand the request |
401 | Unauthorized | The requested page needs a username and a password |
402 | Payment Required | You can not use this code yet |
403 | Forbidden | Access is forbidden to the requested page |
404 | Not Found | The server can not find the requested page. |
405 | Method Not Allowed | The method specified in the request is not allowed. |
406 | Not Acceptable | The server can only generate a response that is not accepted by the client. |
407 | Proxy Authentication Required | You must authenticate with a proxy server before this request can be served. |
408 | Request Timeout | The request took longer than the server was prepared to wait. |
409 | Conflict | The request could not be completed because of a conflict. |
410 | Gone | The requested page is no longer available. |
411 | Length Required | The "Content-Length" is not defined. The server will not accept the request without it. |
412 | Precondition Failed | The precondition given in the request evaluated to false by the server. |
413 | Request Entity Too Large | The server will not accept the request, because the request entity is too large. |
414 | Request-url Too Long | The server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information. |
415 | Unsupported Media Type | The server will not accept the request, because the media type is not supported. |
417 | Expectation Failed | |
500 | Internal Server Error | The request was not completed. The server met an unexpected condition |
501 | Not Implemented | The request was not completed. The server did not support the functionality required. |
502 | Bad Gateway | The request was not completed. The server received an invalid response from the upstream server |
503 | Service Unavailable | The request was not completed. The server is temporarily overloading or down. |
504 | Gateway Timeout | The gateway has timed out. |
505 | HTTP Version Not Supported | The server does not support the "http protocol" version. |
Methods to Set HTTP Status Code:
There are following methods which can be used to set HTTP Status Code in your servlet program. These methods are available with HttpServletResponse object.
S.N. | Method & Description |
---|---|
1 | public void setStatus ( int statusCode ) This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter. |
2 | public void sendRedirect(String url) This method generates a 302 response along with a Location header giving the URL of the new document. |
3 | public void sendError(int code, String message) This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client. |
HTTP Status Code Example:
Following is the example which would send 407 error code to the client browser and browser would show you "Need authentication!!!" message.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class showError extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set error code and reason. response.sendError(407, "Need authentication!!!" ); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Now calling the above servlet would display following result:
HTTP Status 407 - Need authentication!!!
type Status report
messageNeed authentication!!!
descriptionThe client must first authenticate itself with the proxy (Need authentication!!!).
Apache Tomcat/5.5.29
Servlets - Writing Filters
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
There are are various types of filters suggested by the specifications:
Authentication Filters.
Data compression Filters.
Encryption Filters.
Filters that trigger resource access events.
Image Conversion Filters.
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor.
When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
Servlet Filter Methods:
A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods:
S.N. | Method & Description |
---|---|
1 | public void doFilter (ServletRequest, ServletResponse, FilterChain) This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. |
2 | public void init(FilterConfig filterConfig) This method is called by the web container to indicate to a filter that it is being placed into service. |
3 | public void destroy() This method is called by the web container to indicate to a filter that it is being taken out of service. |
Servlet Filter Example:
Following is the Servlet Filter Example that would print the clients IP address and current date time. This example would give you basic understanding of Servlet Filter, but you can write more sophisticated filter applications using the same concept:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Implements Filter class public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException{ // Get init parameter String testParam = config.getInitParameter("test-param"); //Print the init parameter System.out.println("Test Param: " + testParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); // Log the IP address and current timestamp. System.out.println("IP "+ ipAddress + ", Time " + new Date().toString()); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy( ){ /* Called before the Filter instance is removed from service by the web container*/ } }
Compile LogFilter.java in usual way and put your class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
Servlet Filter Mapping in Web.xml:
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is defined and then mapped to a URL pattern. Create the following entry for filter tag in the deployment descriptor file web.xml
<filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
The above filter would apply to all the servlets because we specified /* in our configuration. You can specicy a particular servlet path if you want to apply filter on few servlets only.
Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4J logger to log above log in a separate file.
Using Multiple Filters:
Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you need to create a different mapping as mentioned below:
<filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter> <filter-name>AuthenFilter</filter-name> <filter-class>AuthenFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Filters Application Order:
The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.
For example, above example would apply LogFilter first and then it would apply AuthenFilter to any servlet but the following example would reverse the order:
<filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Servlets - Writing Filters
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
There are are various types of filters suggested by the specifications:
Authentication Filters.
Data compression Filters.
Encryption Filters.
Filters that trigger resource access events.
Image Conversion Filters.
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor.
When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
Servlet Filter Methods:
A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods:
S.N. | Method & Description |
---|---|
1 | public void doFilter (ServletRequest, ServletResponse, FilterChain) This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. |
2 | public void init(FilterConfig filterConfig) This method is called by the web container to indicate to a filter that it is being placed into service. |
3 | public void destroy() This method is called by the web container to indicate to a filter that it is being taken out of service. |
Servlet Filter Example:
Following is the Servlet Filter Example that would print the clients IP address and current date time. This example would give you basic understanding of Servlet Filter, but you can write more sophisticated filter applications using the same concept:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Implements Filter class public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException{ // Get init parameter String testParam = config.getInitParameter("test-param"); //Print the init parameter System.out.println("Test Param: " + testParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); // Log the IP address and current timestamp. System.out.println("IP "+ ipAddress + ", Time " + new Date().toString()); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy( ){ /* Called before the Filter instance is removed from service by the web container*/ } }
Compile LogFilter.java in usual way and put your class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
Servlet Filter Mapping in Web.xml:
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is defined and then mapped to a URL pattern. Create the following entry for filter tag in the deployment descriptor file web.xml
<filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
The above filter would apply to all the servlets because we specified /* in our configuration. You can specicy a particular servlet path if you want to apply filter on few servlets only.
Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4J logger to log above log in a separate file.
Using Multiple Filters:
Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you need to create a different mapping as mentioned below:
<filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter> <filter-name>AuthenFilter</filter-name> <filter-class>AuthenFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Filters Application Order:
The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.
For example, above example would apply LogFilter first and then it would apply AuthenFilter to any servlet but the following example would reverse the order:
<filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Servlets - Exception Handling
When a servlet throws an exception, the web container searches the configurations in web.xml that use the exception-type element for a match with the thrown exception type.
You would have to use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes.
web.xml Configuration:
Consider, you have an ErrorHandler servlet which would be called whenever there is any defined exception or error. Following would be the entry created in web.xml.
<!-- servlet definition --> <servlet> <servlet-name>ErrorHandler</servlet-name> <servlet-class>ErrorHandler</servlet-class> </servlet> <!-- servlet mappings --> <servlet-mapping> <servlet-name>ErrorHandler</servlet-name> <url-pattern>/ErrorHandler</url-pattern> </servlet-mapping> <!-- error-code related error pages --> <error-page> <error-code>404</error-code> <location>/ErrorHandler</location> </error-page> <error-page> <error-code>403</error-code> <location>/ErrorHandler</location> </error-page> <!-- exception-type related error pages --> <error-page> <exception-type> javax.servlet.ServletException </exception-type > <location>/ErrorHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type > <location>/ErrorHandler</location> </error-page>
If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception:
<error-page> <exception-type>java.lang.Throwable</exception-type > <location>/ErrorHandler</location> </error-page>
Following are the points to be noted about above web.xml for Exception Handling:
The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml.
If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), then ErrorHandler servlet would be called.
If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet.
You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept.
Request Attributes - Errors/Exceptions:
Following is the list of request attributes that an error-handling servlet can access to analyse the nature of error/exception.
S.N. | Attribute & Description |
---|---|
1 | javax.servlet.error.status_code This attribute give status code which can be stored and analysed after storing in a java.lang.Integer data type. |
2 | javax.servlet.error.exception_type This attribute gives information about exception type which can be stored and analysed after storing in a java.lang.Class data type. |
3 | javax.servlet.error.message This attribute gives information exact error message which can be stored and analysed after storing in a java.lang.String data type. |
4 | javax.servlet.error.request_uri This attribute gives information about URL calling the servlet and it can be stored and analysed after storing in a java.lang.String data type. |
5 | javax.servlet.error.exception This attribute gives information the exception raised which can be stored and analysed after storing in a java.lang.Throwable data type. |
6 | javax.servlet.error.servlet_name This attribute gives servlet name which can be stored and analysed after storing in a java.lang.String data type. |
Error Handler Servlet Example:
Following is the Servlet Example that would be used as Error Handler in case of any error or exception occurs with your any of the servlet defined.
This example would give you basic understanding of Exception Handling in Servlet, but you can write more sophisticated filter applications using the same concept:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class ErrorHandler extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Analyze the servlet exception Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name"); if (servletName == null){ servletName = "Unknown"; } String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri"); if (requestUri == null){ requestUri = "Unknown"; } // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Error/Exception Information"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n"); if (throwable == null && statusCode == null){ out.println("<h2>Error information is missing</h2>"); out.println("Please return to the <a href=\"" + response.encodeURL("http://localhost:8080/") + "\">Home Page</a>."); }else if (statusCode != null){ out.println("The status code : " + statusCode); }else{ out.println("<h2>Error information</h2>"); out.println("Servlet Name : " + servletName + "</br></br>"); out.println("Exception Type : " + throwable.getClass( ).getName( ) + "</br></br>"); out.println("The request URI: " + requestUri + "<br><br>"); out.println("The exception message: " + throwable.getMessage( )); } out.println("</body>"); out.println("</html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Compile ErrorHandler.java in usual way and put your class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
Let us add the following configuration in web.xml to handle exceptions:
<servlet> <servlet-name>ErrorHandler</servlet-name> <servlet-class>ErrorHandler</servlet-class> </servlet> <!-- servlet mappings --> <servlet-mapping> <servlet-name>ErrorHandler</servlet-name> <url-pattern>/ErrorHandler</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/ErrorHandler</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type > <location>/ErrorHandler</location> </error-page>
Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web Container to call ErrorHandler servlet and display an appropriate message as programmed. For example, if you type a wrong URL then it would display the following result:
The status code : 404
Above code may not work with some web browsers. So try with Mozilla and Safari and it should work.
Servlets - Cookies Handling
Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
This chapter will teach you how to set or reset cookies, how to access them and how to delete them.
The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this:
GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz
A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects.
Servlet Cookies Methods:
Following is the list of useful methods which you can use while manipulating cookies in servlet.
S.N. | Method & Description |
---|---|
1 | public void setDomain(String pattern) This method sets the domain to which cookie applies, for example tutorialspoint.com. |
2 | public String getDomain() This method gets the domain to which cookie applies, for example tutorialspoint.com. |
3 | public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session. |
4 | public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. |
5 | public String getName() This method returns the name of the cookie. The name cannot be changed after creation. |
6 | public void setValue(String newValue) This method sets the value associated with the cookie. |
7 | public String getValue() This method gets the value associated with the cookie. |
8 | public void setPath(String uri) This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. |
9 | public String getPath() This method gets the path to which this cookie applies. |
10 | public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections. |
11 | public void setComment(String purpose) This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user. |
12 | public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment. |
Setting Cookies with Servlet:
Setting cookies with servlet involves three steps:
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the following characters:
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:
response.addCookie(cookie);
Example:
Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>: " + request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " + request.getParameter("last_name") + "\n" + "</ul>\n" + "</body></html>"); } }
Compile above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet.
<html> <body> <form action="HelloForm" method="GET"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html>
Keep above HTML content in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.
Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.
Reading Cookies with Servlet:
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.
Example:
Let us read cookies which we have set in previous example:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class ReadCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } }
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as "John" and last_name cookie as "Player" then running http://localhost:8080/ReadCookies would display the following result:
Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: Player
Delete Cookies with Servlet:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:
Read an already exsiting cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Add this cookie back into response header.
Example:
Following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null value for first_name.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class DeleteCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Delete Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2> Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie : " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } }
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running http://localhost:8080/DeleteCookies would display the following result:
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as follows:
Found Cookies Name and Value
Name : last_name, Value: Player
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies.
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.
- Non-persistent cookie
- Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.
Advantage of Cookies
- Simplest technique of maintaining the state.
- Cookies are maintained at client side.
Disadvantage of Cookies
- It will not work if cookie is disabled from the browser.
- Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.
Constructor of Cookie class
Constructor | Description |
---|---|
Cookie() | constructs a cookie. |
Cookie(String name, String value) | constructs a cookie with a specified name and value. |
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Method | Description |
---|---|
public void setMaxAge(int expiry) | Sets the maximum age of the cookie in seconds. |
public String getName() | Returns the name of the cookie. The name cannot be changed after creation. |
public String getValue() | Returns the value of the cookie. |
public void setName(String name) | changes the name of the cookie. |
public void setValue(String value) | changes the value of the cookie. |
Other methods required for using Cookies
For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are:
|
How to create Cookie?
Let's see the simple code to create cookie.
How to delete Cookie?
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
How to get Cookies?
Let's see the simple code to get all the cookies.
Simple example of Servlet Cookies
In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value.
index.html
FirstServlet.java
SecondServlet.java
web.xml
Output
Servlets - Session Tracking
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
- Cookies
- Hidden Form Field
- URL Rewriting
- HttpSession
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web server:
Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.
Hidden Form Fields:
A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden" name="sessionid" value="12345">
This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.
The HttpSession Object:
Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below:
HttpSession session = request.getSession();
You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object:
S.N. | Method & Description |
---|---|
1 | public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. |
2 | public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. |
3 | public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
4 | public String getId() This method returns a string containing the unique identifier assigned to this session. |
5 | public long getLastAccessedTime() This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. |
6 | public int getMaxInactiveInterval() This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. |
7 | public void invalidate() This method invalidates this session and unbinds any objects bound to it. |
8 | public boolean isNew( This method returns true if the client does not yet know about the session or if the client chooses not to join the session. |
9 | public void removeAttribute(String name) This method removes the object bound with the specified name from this session. |
10 | public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. |
11 | public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. |
Session Tracking Example:
This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create a session object if it is already not created. HttpSession session = request.getSession(true); // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check if this is new comer on your web page. if (session.isNew()){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); } else { visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); } session.setAttribute(visitCountKey, visitCount); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<h2 align=\"center\">Session Infomation</h2>\n" + "<table border=\"1\" align=\"center\">\n" + "<tr bgcolor=\"#949494\">\n" + " <th>Session info</th><th>value</th></tr>\n" + "<tr>\n" + " <td>id</td>\n" + " <td>" + session.getId() + "</td></tr>\n" + "<tr>\n" + " <td>Creation Time</td>\n" + " <td>" + createTime + " </td></tr>\n" + "<tr>\n" + " <td>Time of Last Access</td>\n" + " <td>" + lastAccessTime + " </td></tr>\n" + "<tr>\n" + " <td>User ID</td>\n" + " <td>" + userID + " </td></tr>\n" + "<tr>\n" + " <td>Number of visits</td>\n" + " <td>" + visitCount + "</td></tr>\n" + "</table>\n" + "</body></html>"); } }
Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now running http://localhost:8080/SessionTrack would display the following result when you would run for the first time:
Welcome to my website
Session Infomation
Session info | value |
---|---|
id | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
Time of Last Access | Tue Jun 08 17:26:40 GMT+04:00 2010 |
User ID | ABCD |
Number of visits | 0 |
Now try to run the same servlet for second time, it would display following result.
Welcome Back to my website
Session Infomation
info type | value |
---|---|
id | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
Time of Last Access | Tue Jun 08 17:26:40 GMT+04:00 2010 |
User ID | ABCD |
Number of visits | 1 |
Deleting Session Data:
When you are done with a user's session data, you have several options:
Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key.
Delete the whole session: You can call public void invalidate() method to discard an entire session.
Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.
<session-config> <session-timeout>15</session-timeout> </session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.
Servlets - File Uploading
A Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded file could be a text file or image file or any document.
Creating a File Upload Form:
The following HTM code below creates an uploader form. Following are the important points to be noted down:
The form method attribute should be set to POST method and GET method can not be used.
The form enctype attribute should be set to multipart/form-data.
The form action attribute should be set to a servlet file which would handle file uploading at backend server. Following example is using UploadServlet servlet to upload file.
To upload a single file you should use a single <input .../> tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.
<html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action="UploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" size="50" /> <br /> <input type="submit" value="Upload File" /> </form> </body> </html>
This will display following result which would allow to select a file from local PC and when user would click at "Upload File", form would be submitted along with the selected file:
File Upload: Select a file to upload:
NOTE: This is just dummy form and would not work.
Writing Backend Servlet:
Following is the servlet UploadServlet which would take care of accepting uploaded file and to store it in directory <Tomcat-installation-directory>/webapps/data. This directory name could also be added using an external configuration such as a context-param element in web.xml as follows:
<web-app> .... <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:\apache-tomcat-5.5.29\webapps\data\ </param-value> </context-param> .... </web-app>
Following is the source code for UploadServlet which can handle multiple file uploading at a time. Before procedding you have make sure the followings:
Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from http://commons.apache.org/fileupload/.
FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from http://commons.apache.org/io/.
While testing following example, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded.
Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data well in advance.
// Import required java libraries import java.io.*; import java.util.*; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.output.*; public class UploadServlet extends HttpServlet { private boolean isMultipart; private String filePath; private int maxFileSize = 50 * 1024; private int maxMemSize = 4 * 1024; private File file ; public void init( ){ // Get the file location where it would be stored. filePath = getServletContext().getInitParameter("file-upload"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter( ); if( !isMultipart ){ out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try{ // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while ( i.hasNext () ) { FileItem fi = (FileItem)i.next(); if ( !fi.isFormField () ) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if( fileName.lastIndexOf("\\") >= 0 ){ file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ; }else{ file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ; } fi.write( file ) ; out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); }catch(Exception ex) { System.out.println(ex); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required."); } }
Compile and Running Servlet:
Compile above servlet UploadServlet and create required entry in web.xml file as follows.
<servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping>
Now try to upload files using the HTML form which you created above. When you would try http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from your local machine.
File Upload:Select a file to upload:
If your servelt script works fine, your file should be uploaded in c:\apache-tomcat-5.5.29\webapps\data\ directory.
Servlet - Handling Date
One of the most important advantages of using Servlet is that you can use most of the methods available in core Java. This tutorial would take you through Java provided Date class which is available in java.util package, this class encapsulates the current date and time.
The Date class supports two constructors. The first constructor initializes the object with the current date and time.
Date( )
The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970
Date(long millisec)
Once you have a Date object available, you can call any of the following support methods to play with dates:
SN | Methods with Description |
---|---|
1 | boolean after(Date date) Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false. |
2 | boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false. |
3 | Object clone( ) Duplicates the invoking Date object. |
4 | int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. |
5 | int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. |
6 | boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false. |
7 | long getTime( ) Returns the number of milliseconds that have elapsed since January 1, 1970. |
8 | int hashCode( ) Returns a hash code for the invoking object. |
9 | void setTime(long time) Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970. |
10 | String toString( ) Converts the invoking Date object into a string and returns the result. |
Getting Current Date & Time
This is very easy to get current date and time in Java Servlet. You can use a simple Date object with toString() method to print current date and time as follows:
// Import required java libraries import java.io.*; import java.util.Date; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class CurrentDate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Display Current Date & Time"; Date date = new Date(); String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<h2 align=\"center\">" + date.toString() + "</h2>\n" + "</body></html>"); } }
Now let us compile above servlet and create appropriate entries in web.xml and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result:
Display Current Date & Time
Mon Jun 21 21:46:49 GMT+04:00 2010
Try to refersh URL http://localhost:8080/CurrentDate and you would find difference in seconds everytime you would refresh.
Date Comparison:
As I mentioned above you can use all the available Java methods in your Servlet. In case you need to compare two dates, following are the methods:
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
Date Formatting using SimpleDateFormat:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Let us modify above example as follows:
// Import required java libraries import java.io.*; import java.text.*; import java.util.Date; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class CurrentDate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Display Current Date & Time"; Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<h2 align=\"center\">" + ft.format(dNow) + "</h2>\n" + "</body></html>"); } }
Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result:
Display Current Date & Time
Mon 2010.06.21 at 10:06:44 PM GMT+04:00
Simple DateFormat format codes:
To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:
Character | Description | Example |
---|---|---|
G | Era designator | AD |
y | Year in four digits | 2001 |
M | Month in year | July or 07 |
d | Day in month | 10 |
h | Hour in A.M./P.M. (1~12) | 12 |
H | Hour in day (0~23) | 22 |
m | Minute in hour | 30 |
s | Second in minute | 55 |
S | Millisecond | 234 |
E | Day in week | Tuesday |
D | Day in year | 360 |
F | Day of week in month | 2 (second Wed. in July) |
w | Week in year | 40 |
W | Week in month | 1 |
a | A.M./P.M. marker | PM |
k | Hour in day (1~24) | 24 |
K | Hour in A.M./P.M. (0~11) | 10 |
z | Time zone | Eastern Standard Time |
' | Escape for text | Delimiter |
" | Single quote | ` |
For a complete list of constant available methods to manipulate date, you can refer to standard Java documentation.
Servlets - Hits Counter
Hit Counter for a Web Page:
Many times you would be interested in knowing total number of hits on a particular page of your website. It is very simple to count these hits using a servlet because the life cycle of a servlet is controlled by the container in which it runs.
Following are the steps to be taken to implement a simple page hit counter which is based on Servlet Life Cycle:
Initialize a global variable in init() method.
Increase global variable every time either doGet() or doPost() method is called.
If required, you can use a database table to store the value of global variable in destroy() method. This value can be read inside init() method when servlet would be initialized next time. This step is optional.
If you want to count only unique page hits with-in a session then you can use isNew() method to check if same page already have been hit with-in that session. This step is optional.
You can display value of the global counter to show total number of hits on your web site. This step is also optional.
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.
Example:
This example shows how to implement a simple page hit counter:
import java.io.*; import java.sql.Date; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PageHitCounter extends HttpServlet{ private int hitCount; public void init() { // Reset hit counter. hitCount = 0; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // This method executes whenever the servlet is hit // increment hitCount hitCount++; PrintWriter out = response.getWriter(); String title = "Total Number of Hits"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<h2 align=\"center\">" + hitCount + "</h2>\n" + "</body></html>"); } public void destroy() { // This is optional step but if you like you // can write hitCount value in your database. } }
Now let us compile above servlet and create following entries in web.xml
.... <servlet> <servlet-name>PageHitCounter</servlet-name> <servlet-class>PageHitCounter</servlet-class> </servlet> <servlet-mapping> <servlet-name>PageHitCounter</servlet-name> <url-pattern>/PageHitCounter</url-pattern> </servlet-mapping> ....
Now call this servlet using URL http://localhost:8080/PageHitCounter. This would increase counter by one every time this page gets refreshed and it would display following result:
Total Number of Hits
6
Hit Counter for a Website:
Many times you would be interested in knowing total number of hits on your whole website. This is also very simple in Servlet and we can achieve this using filters.
Following are the steps to be taken to implement a simple website hit counter which is based on Filter Life Cycle:
Initialize a global variable in init() method of a filter.
Increase global variable every time doFilter method is called.
If required, you can use a database table to store the value of global variable in destroy() method of filter. This value can be read inside init() method when filter would be initialized next time. This step is optional.
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.
Example:
This example shows how to implement a simple website hit counter:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class SiteHitCounter implements Filter{ private int hitCount; public void init(FilterConfig config) throws ServletException{ // Reset hit counter. hitCount = 0; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // increase counter by one hitCount++; // Print the counter. System.out.println("Site visits count :"+ hitCount ); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy() { // This is optional step but if you like you // can write hitCount value in your database. } }
Now let us compile above servlet and create following entries in web.xml
.... <filter> <filter-name>SiteHitCounter</filter-name> <filter-class>SiteHitCounter</filter-class> </filter> <filter-mapping> <filter-name>SiteHitCounter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ....
Now call any URL like URL http://localhost:8080/. This would increase counter by one every time any page gets a hit and it would display following message in the log:
Site visits count : 1 Site visits count : 2 Site visits count : 3 Site visits count : 4 Site visits count : 5 ..................
Servlets - Auto Page Refresh
Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using referesh or reload button with your browser.
Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.
The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.
Auto Page Refresh Example:
This example shows how a servlet performs auto page refresh using setIntHeader() method to set Refresh header.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class Refresh extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Set response content type response.setContentType("text/html"); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriter out = response.getWriter(); String title = "Auto Page Refresh using Servlet"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p>Current Time is: " + CT + "</p>\n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Now let us compile above servlet and create following entries in web.xml
.... <servlet> <servlet-name>Refresh</servlet-name> <servlet-class>Refresh</servlet-class> </servlet> <servlet-mapping> <servlet-name>Refresh</servlet-name> <url-pattern>/Refresh</url-pattern> </servlet-mapping> ....
Now call this servlet using URL http://localhost:8080/Refresh which would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result:
Auto Page Refresh using Servlet
Current Time is: 9:44:50 PM
Servlets - Sending Email
To send an email using your a Servlet is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.
You can download latest version of JavaMail (Version 1.2) from Java's standard website.
You can download latest version of JAF (Version 1.1.1) from Java's standard website.
Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH.
Send a Simple Email:
Here is an example to send a simple email from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. Same time make sure all the jar files from Java Email API package and JAF package are available in CLASSPATH.
// File Name SendEmail.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport.send(message); String title = "Send Email"; String res = "Sent message successfully...."; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p align=\"center\">" + res + "</p>\n" + "</body></html>"); }catch (MessagingException mex) { mex.printStackTrace(); } } }
Now let us compile above servlet and create following entries in web.xml
.... <servlet> <servlet-name>SendEmail</servlet-name> <servlet-class>SendEmail</servlet-class> </servlet> <servlet-mapping> <servlet-name>SendEmail</servlet-name> <url-pattern>/SendEmail</url-pattern> </servlet-mapping> ....
Now call this servlet using URL http://localhost:8080/SendEmail which would send an email to given email ID abcd@gmail.com and would display following response:
Send Email
Sent message successfully....
If you want to send an email to multiple recipients then following methods would be used to specify multiple email IDs:
void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException
Here is the description of the parameters:
type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example Message.RecipientType.TO
addresses: This is the array of email ID. You would need to use InternetAddress() method while specifying email IDs
Send an HTML Email:
Here is an example to send an HTML email from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. Same time make sure all the jar files from Java Email API package and JAF package ara available in CLASSPATH.
This example is very similar to previous one, except here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message.
Using this example, you can send as big as HTML content you like.
// File Name SendEmail.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Send the actual HTML message, as big as you like message.setContent("<h1>This is actual message</h1>", "text/html" ); // Send message Transport.send(message); String title = "Send Email"; String res = "Sent message successfully...."; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p align=\"center\">" + res + "</p>\n" + "</body></html>"); }catch (MessagingException mex) { mex.printStackTrace(); } } }
Compile and run above servlet to send HTML message on a given email ID.
Send Attachment in Email:
Here is an example to send an email with attachment from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email.
// File Name SendEmail.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText("This is message body"); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = "file.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart ); // Send message Transport.send(message); String title = "Send Email"; String res = "Sent message successfully...."; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p align=\"center\">" + res + "</p>\n" + "</body></html>"); }catch (MessagingException mex) { mex.printStackTrace(); } } }
Compile and run above servlet to send a file as an attachement along with a message on a given email ID.
User Authentication Part:
If it is required to provide user ID and Password to the email server for authentication purpose then you can set these properties as follows:
props.setProperty("mail.user", "myuser"); props.setProperty("mail.password", "mypwd");
Rest of the email sending mechanism would remain as explained above.
Servlets - Debugging
It is always difficult to testing/debugging a servlets. Servlets tend to involve a large amount of client/server interaction, making errors likely but hard to reproduce.
Here are a few hints and suggestions that may aid you in your debugging.
System.out.println()
System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Additionally:
Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications.
Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when timing is crucial.
Following is the syntax to use System.out.println():
System.out.println("Debugging message");
All the messages generated by above syntax would be logged in web server log file.
Message Logging:
It is always great idea to use proper logging method to log all the debug, warning and error messages using a standard logging method. I use log4J to log all the messages.
The Servlet API also provides a simple way of outputting information by using the log() method as follows:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ContextLog extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { String par = request.getParameter("par1"); //Call the two ServletContext.log methods ServletContext context = getServletContext( ); if (par == null || par.equals("")) //log version with Throwable parameter context.log("No message received:", new IllegalStateException("Missing parameter")); else context.log("Here is the visitor's message: " + par); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter( ); String title = "Context Log"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<h2 align=\"center\">Messages sent</h2>\n" + "</body></html>"); } //doGet }
The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs are found in <Tomcat-installation-directory>/logs.
The log files do give an indication of new emerging bugs or the frequency of problems. For that reason it's good to use the log() function in the catch clause of exceptions which should normally not occur.
Using JDB Debugger:
You can debug servlets with the same jdb commands you use to debug an applet or an application.
To debug a servlet, we can debug sun.servlet.http.HttpServer, then watch as HttpServer executes servlets in response to HTTP requests we make from a browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer.
Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for servlets, you have to help your debugger by doing the following:
Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes.
Set your debugger's classpath so that it can also find your servlets and support classes, typically server_root/servlets and server_root/classes.
You normally wouldn't want server_root/servlets in your classpath because it disables servlet reloading. This inclusion, however, is useful for debugging. It allows your debugger to set breakpoints in a servlet before the custom servlet loader in HttpServer loads the servlet.
Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever servlet you're interested in debugging, then use a web browser to make a request to the HttpServer for the given servlet (http://localhost:8080/servlet/ServletToDebug). You should see execution stop at your breakpoints.
Using Comments:
Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process.
The Servlet uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem.
Client and Server Headers:
Sometimes when a servlet doesn't behave as expected, it's useful to look at the raw HTTP request and response. If you're familiar with the structure of HTTP, you can read the request and response and see exactly what exactly is going with those headers.
Important Debugging Tips:
Here is a list of some more debugging tips on servlet debugging:
Be aware that server_root/classes doesn't reload and that server_root/servlets probably does.
Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu.
Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.
Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away.
Servlets - Internationalization
Before we proceed, let me explain three important terms:
Internationalization (i18n): This means enabling a web site to provide different versions of content translated into the visitor's language or nationality.
Localization (l10n): This means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.
locale: This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which is separated by an underscore. For example "en_US" represents english locale for US.
There are number of items which should be taken care while building up a global website. This tutorial would not give you complete detail on this but it would give you a good example on how you can offer your web page in different languages to internet community by differentiating their location ie. locale.
A servlet can pickup appropriate version of the site based on the requester's locale and provide appropriate site version according to the local language, culture and requirements. Following is the method of request object which returns Locale object.
java.util.Locale request.getLocale()
Detecting Locale:
Following are the important locale methods which you can use to detect requester's location, language and of course locale. All the below methods display country name and language name set in requester's browser.
S.N. | Method & Description |
---|---|
1 | String getCountry() This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format. |
2 | String getDisplayCountry() This method returns a name for the locale's country that is appropriate for display to the user. |
3 | String getLanguage() This method returns the language code in lower case for this locale in ISO 639 format. |
4 | String getDisplayLanguage() This method returns a name for the locale's language that is appropriate for display to the user. |
5 | String getISO3Country() This method returns a three-letter abbreviation for this locale's country. |
6 | String getISO3Language() This method returns a three-letter abbreviation for this locale's language. |
Example:
This example shows how you display a language and associated country for a request:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; public class GetLocale extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the client's Locale Locale locale = request.getLocale(); String language = locale.getLanguage(); String country = locale.getCountry(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Detecting Locale"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + language + "</h1>\n" + "<h2 align=\"center\">" + country + "</h2>\n" + "</body></html>"); } }
Languages Setting:
A servlet can output a page written in a Western European language such as English, Spanish, German, French, Italian, Dutch etc. Here it is important to set Content-Language header to display all the characters properly.
Second point is to display all the special characters using HTML entities, For example, "ñ" represents "ñ", and "¡" represents "¡" as follows:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; public class DisplaySpanish extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Set spanish language code. response.setHeader("Content-Language", "es"); String title = "En Español"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1>" + "En Español:" + "</h1>\n" + "<h1>" + "¡Hola Mundo!" + "</h1>\n" + "</body></html>"); } }
Locale Specific Dates:
You can use the java.text.DateFormat class and its static getDateTimeInstance( ) method to format date and time specific to locale. Following is the example which shows how to format dates specific to a given locale:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; import java.text.DateFormat; import java.util.Date; public class DateLocale extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Get the client's Locale Locale locale = request.getLocale( ); String date = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.SHORT, locale).format(new Date( )); String title = "Locale Specific Dates"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + date + "</h1>\n" + "</body></html>"); } }
Locale Specific Currency
You can use the java.txt.NumberFormat class and its static getCurrencyInstance( ) method to format a number, such as a long or double type, in a locale specific curreny. Following is the example which shows how to format currency specific to a given locale:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; import java.text.NumberFormat; import java.util.Date; public class CurrencyLocale extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Get the client's Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getCurrencyInstance(locale); String formattedCurr = nft.format(1000000); String title = "Locale Specific Currency"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + formattedCurr + "</h1>\n" + "</body></html>"); } }
Locale Specific Percentage
You can use the java.txt.NumberFormat class and its static getPercentInstance( ) method to get locale specific percentage. Following is the example which shows how to format percentage specific to a given locale:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; import java.text.NumberFormat; import java.util.Date; public class PercentageLocale extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Get the client's Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getPercentInstance(locale); String formattedPerc = nft.format(0.51); String title = "Locale Specific Percentage"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + formattedPerc + "</h1>\n" + "</body></html>"); } }
nice post..
ReplyDelete. net online training
dot net online training hydarabad
Thanks for sharing such useful information. It is crisp and self-explanatory.
ReplyDeleteOracle Java Certifications