Java Servlet Tutorial
Java Servlet Tutorial
ii
Contents
Introduction
1.1
Servlet Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
Merits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Life Cycle
Container
3.1
Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2
Filter
6
12
5.1
Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.2
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Session
19
6.1
Session Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
6.2
6.3
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Exception Handling
23
7.1
7.2
Exception-Type Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Debugging
24
8.1
Message Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8.2
Java Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8.3
Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8.4
Refresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Internationalization
26
9.1
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
9.2
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
iii
10 Reference
29
11 Conclusion
30
12 Download
31
iv
Preface
Java Servlets is a Java based web technology. Java Servlet technology provides Web developers with a simple, consistent
mechanism for extending the functionality of a Web server and for accessing existing business systems.
A servlet can almost be thought of as an applet that runs on the server side-without a face. Java servlets make many Web
applications possible.
Java Servlets comprise a fundamental part of the Java Enterprise Edition (Java EE). Please note that Java Servlets have to be
executed inside a Servlet compatible Servlet Container (e.g. web server) in order to work.
This tutorial works as a comprehensive, kick-start guide for your Java Servlet based code.
vi
1 / 31
Chapter 1
Introduction
Servlet is a Java programming language class, part of Java Enterprise Edition (Java EE). Sun Microsystems developed its first
version 1.0 in the year 1997. Its current Version is Servlet 3.1.
Servlets are used for creating dynamic web applications in java by extending the capability of a server. It can run on any web
server integrated with a Servlet container.
1.1
Servlet Process
1.2
Merits
2 / 31
The Servlet API inherits all the features of the Java platform.
It builds and modifies the security logic for server-side extensions.
Servlets inherit the security provided by the Web Server.
In Servlet, only a single instance of the requests runs concurrently. It does not run in a separate process. So, it saves the
memory by removing the overhead of creating a new process for each request.
3 / 31
Chapter 2
Life Cycle
Servlet lifecycle describes how the servlet container manages the servlet object.
Load Servlet Class
Servlet Instance is created by the web container when the servlet class is loaded
init():This is called only once when the servlet is created. There is no need to call it again and again for multiple requests.
public void init() throws ServletException {
}
service(): It is called by the web container to handle request from clients. Here the actual functioning of the code is done.
The web container calls this method each time when request for the servlet is received.
It calls doGet(), doPost(), doTrace(), doPut(), doDelete() and other methods
doGet():
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// code
}
doPost():
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// code
}
destroy(): It is used to clean resources and called before removing the servlet instance.
public void destroy()
4 / 31
5 / 31
Chapter 3
Container
It is known as servlet engine which manages Java Servlet components on top of a web server to the request send by the client.
3.1
Services
3.2
The servlet container can be configured with the web server to manage servlets in three ways listed below:
Standalone container
In-process container
Out-process container
Standalone container: In this type the Web Server functionality is taken by the Servlet container. Here, the container is strongly
coupled with the Web server.
In-Process container: In this the container runs within the Web server process.
Out-Process container: In this type there is a need to configure the servlet container to run outside the Web server process. It is
used in some cases like if there is a need to run Servlets and Servlet container in different process/systems.
6 / 31
Chapter 4
7 / 31
8 / 31
9 / 31
Directory Structure:
Here,
<servlet-name>: name given to Servlet
<servlet-class>: servlet class
<servlet-mapping>: maps internal name to URL
<url-pattern>: link displays when Servlet runs
The hyperlink Next is mentioned as ServletDemo. So, when the user will click on it, the page will redirect to ServletDemo servlet
whose url-pattern is mentioned as ServetDemo:
Listing 2: index.html
<html>
<head>
<title>Welcome</title>
<meta charset="UTF-8">
10 / 31
Listing 3: ServletDemo.java
import
import
import
import
import
import
java.io.IOException;
java.io.PrintWriter;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
11 / 31
{
out.close();
}
}
}
12 / 31
Chapter 5
Filter
Filters transform the content of requests, responses, and header information from one format to another. These are reusable
codes.
Filter class is declared in the deployment descriptor.
It is used to write reusable components.
The request is process before it is called using filters.
It can be used under a web application for some tasks like:
Validation
Compression
Verification
Internationalization
5.1
Interface
Methods
init(FilterConfig)
doFilter(ServletRequest,
ServletResponse, FilterChain)
destroy()
13 / 31
Description
This method initializes a filter
This method encapsulates the service logic on
ServletRequest to generate ServletResponse. FilterChain is
to forward request/response pair to the next filter.
It destroys the instance of the filter class.
FilterConfig
Its object is used when the filters are initialized. Deployment descriptor (web.xml) consists of configuration information. The
object of FilterConfig interface is used to fetch configuration information about filter specified in web.xml. Its methods are
mentioned below:
Methods
getFilterName()
getInitParameter(String)
getInitParameterNames()
getServletContext()
Description
It returns the name of filter in web.xml
It returns specified initialization parameters value from
web.xml
It returns enumeration of all initialization parameters of
filter.
It returns ServletContext object.
FilterChain
It stores information about more than 1 filter (chain). All filters in this chain should be applied on request before processing of a
request.
5.2
Example
This is an example showing filters application in NetBeansIDE. Create a WebApplication project WebApplicationFilterDemo in
the same ways as shown under Demo section. New Filter can be added in the web application by Right Clicking on Project
Directory New Filter
14 / 31
15 / 31
Configure Filter Deployment by checking "Add information to deployment descriptor (web.xml)". Now, the Next button is
disabled here due to an error highlighted in Figure 13. The error "Enter at least one URL pattern" can be solved by clicking on
"New".
Figure 5.4: Configure Filter Deployment by checking "Add information to deployment descriptor(web.xml)"
Now, filter is mapped by adding URL-pattern as shown in Figure 15.
16 / 31
17 / 31
Listing 4: web.xml
The Filter NewFilter can be applied to every servlet as /* is specified here for URL-pattern.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3. org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<filter>
<filter-name>NewFilter</filter-name>
<filter-class>NewFilter</filter-class>
<init-param>
newParam</param-name>
<param-value>valueOne</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>NewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Listing 5: NewFilter.java
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.*;
18 / 31
19 / 31
Chapter 6
Session
It is a collection of HTTP requests between client and server. The session is destroyed when it expires and its resources are back
to the servlet engine.
6.1
Session Handling
It is a means to keep track of session data. This represents the data transferred in a session. It is used when session data from
one session may be required by a web server for completing tasks in same or different sessions. Session handling is also known
assession tracking.
6.2
20 / 31
setComment(String)
getComment()
setVersion(String)
getVersion()
setDomain(String)
setPath(String)
getPath()
setSecure(boolean)
getSecure(boolean)
HTTP session: It provides asession management service implemented through HttpSession object.
Some HttpSession object methods are listed here; this is referred from the official Oracle Documentation:
Method
public Object getAttribute(String name)
public Enumeration getAttributeNames()
public String getId()
public long getCreationTime()
public long getLastAccessedTime()
public int getMaxInactiveInterval()
6.3
Description
It returns the object bound with the specified name in this
session or null if no object is bound under the name.
It returns Enumeration of String objects containing the
names of all the objects bound to this session.
It returns a string containing the unique identifier assigned
to this session.
It returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970 GMT.
It returns the last time the client sent a request associated
with this session.
It returns the maximum time interval, in seconds that the
servlet container will keep this session open between client
accesses.
It Invalidates this session then unbinds any objects bound
to it.
It returns true if the client does not yet know about the
session or if the client chooses not to join the session.
Example
Session Information like session id, session creation time, last accessed time and others is printed under this example.
Listing 6: ServletSession.java
import
import
import
import
import
import
import
import
java.io.IOException;
java.io.PrintWriter;
java.util.Date;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
javax.servlet.http.HttpSession;
21 / 31
22 / 31
23 / 31
Chapter 7
Exception Handling
Exceptions are used to handle errors. It is a reaction to unbearable conditions. Here comes the role of web.xml i.e. deployment
description which is used to run JSP and servlet pages. The container searches the configurations in web.xml for a match. So, in
web.xml use these exception-type elements for match with the thrown exception type when a servlet throws an exception.
7.1
The /HandlerClass servlet gets called when an error with status code 403 occurs as shown below:
Listing 7: For Error code 403
<error-page>
<error-code>403</error-code>
<location>/HandlerClass</location>
</error-page>
7.2
Exception-Type Configuration
If the application throws IOException, then /HandlerClass servlet gets called by the container:
Listing 8: For Exception Type IOException
<error-page>
<exception-type>java.io.IOException</exception-type >
<location>/HandlerClass</location>
</error-page>
If you want to avoid the overhead of adding separate elements, then use java.lang.Throwable as exception-type:
Listing 9: For all exceptions mention java.lang.Throwable:
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/HandlerClass</location>
</error-page>
24 / 31
Chapter 8
Debugging
Client-server interactions are in large number in Servlets. This makes errors difficult to locate. Different ways can be followed
for location warnings and errors.
8.1
Message Logging
Logs are provided for getting information about warning and error messages. For this a standard logging method is used. Servlet
API can generate this information using log() method. Using Apache Tomcat, these logs can be found in TomcatDirectory/logs.
8.2
Java Debugger
Servlets can be debugged using JDB Debugger i.e. Java Debugger. In this the program being debugged is sun.servlet.http.HttpServer.
Set debuggers class path for finding the following classes:
servlet.http.HttpServer
server_root/servlets and server_root/classes: Through this the debugger sets breakpoints in a servlet.
8.3
Headers
Users should have some information related to structure of HTTP headers. Issues can be judged using them which can further
locate some unknown errors. Information related to HTTP headers can help you in locating errors. Studying request and response
can help in guessing what is not going well.
8.4
Refresh
Refresh your browsers web page to avoid it from caching previous request. At some stages, browser shows request performed
previously. This is a known point but can be a problem for those who are working correctly but unable to display the result
properly.
Listing 21: ServletDebugging.java
Here, Servlet Debugging is shown which displays the errors in Tomcat log.
import
import
import
import
import
import
import
25 / 31
java.io.IOException;
java.io.PrintWriter;
javax.servlet.ServletContext;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
26 / 31
Chapter 9
Internationalization
For building a global website, some important points are considered which includes language related to users nationality. Internationalization isenabling a website for providing content translated in different languages according to users nationality.
9.1
Methods
For finding visitors local region and language, these methods are used:
Method
String
String
String
String
String
String
9.2
getCountry()
getDisplayCountry()
getLanguage()
getDisplayLanguage()
getISO3Country()
getISO3Language()
Description
Returns the country code.
Returns a name for the visitors country.
Returns the language code.
Returns a name for the visitors language.
Returns a three-letter abbreviation for the visitors country.
Returns a three-letter abbreviation for the visitors language.
Example
The example displays the current locale of a user. Following project is created in NetBeansIDE:
Project Name: WebApplicationInternationalization
Project Location: C:\Users\Test\Documents\NetBeansProjects
Servlet: ServletLocale
URL Pattern: /ServletLocale
java.io.IOException;
java.io.PrintWriter;
java.util.Locale;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
27 / 31
28 / 31
29 / 31
Chapter 10
Reference
Websites
Official Oracle Documentation
Sun Developer Network
Free NetBeans Download
Free Apache Download
Free Java Download
Books
Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam, by Bryan Basham, Kathy Sierra ,
Bert Bates
Servlet and JSP (A Tutorial), by Budi Kurniawan
30 / 31
Chapter 11
Conclusion
Servlet is fast in performance and easy to use when compared with traditional Common Gateway Interfaces (CGI). Through this
guide you can easily learn the concepts related to Java Servlets. The project codes are developed under NetBeansIDE, so you
will get an idea about some of its amazing user-friendly features as well.
Chapter 12
Download
You can download the full source code of this tutorial here: Servlet_Project_Code
31 / 31