UNIT6
UNIT6
JAVA SERVLETS
In the early days, web servers only deliver static contents (all contents appearing on Web pages is
placed manually by the web developers) in response to a client’s request. Then Java servlets came into
picture which is server-side programs that handle client’s requests and return a dynamic page as a
response for each request. This dynamic response could be based on user's input. The pages are called
“dynamic” because their content is generated “on the fly” each time a page is requested by the web
site visitor.
In order to dynamically generate the web page on the server side ,web server uses Servlet containers.
A Servlet container can have one or more servlets. So it act as a container for servlets. Java servlets
typically run on the HTTP protocol. As we know that HTTP is an asymmetrical request-response
protocol. Its means that client sends a request message to the server, and the server returns a response
message as illustrated in fig .A Java Servlet is a Java object that responds to HTTP requests. It runs
inside a Servlet container.
A Java web application can contain one or more servlets and other components also like Java Server
Pages (JSP), Java Server Faces (JSF) and Web Services. A Servlet container can run multiple web
applications at the same time.
A servlet is an implementation of Java that aims to provide the same service as CGI does, but instead
of programs compiled in the native operating system, it compiles into the Java bytecode which is then
run in the Java virtual machine as shown below.
Java source code Java Compiler Byte code JVM Machine code
(.java file) (.class file)
SERVLET API
The Servlet API comes in Two Java packages. The packages are as follows.
1.javax.servlet
The javax.servlet package is used for serving protocol-less requests. It contains the interfaces and
classes that every servlet must implements and extends respectively. Every servlet must implement
the Servlet interface in one form or another. The abstract GenericServlet class provides the framework
for developing basic servlets. Following table lists some of the interfaces and classes of javax.servlet
package.
2 ServletRequest ServletInputStream
3 ServletResponse ServletOutputStream
4 RequestDispatcher ServletRequestWrapper
5 ServletConfig ServletResponseWrapper
6 ServletContext ServletRequestEvent
7 SingleThreadModel ServletContextEvent
8 Filter ServletRequestAttributeEvent
9 FilterConfig ServletContextAttributeEvent
10 ServletRequestListener ServletException
2. javax.servlet.http.
The javax.servlet.http package is used for the development of servlets that use the HTTP protocol.
The abstract HttpServlet class extends javax.servlet.GenericServlet and serves as the base class for
HTTP servlets. HttpServletRequest and HttpServletResponse interfaces allow additional interaction
with the client. This package also includes HttpSession and some related classes to support session
tracking. Following table lists some of the interfaces and classes of javax.servlet.http package.
A servlet's life cycle is managed via the init(), service() and destroy() methods.
A web server communicates with a servlet through a simple interface javax.servlet.Servlet which
comprised of following methods:
• init()
• service()
• destroy()
The init() method is guaranteed to finish before any other calls are made to the servlet--such as a call
to the service() method.
Note that init() will only be called once; it will not be called again unless the servlet has been
unloaded and then reloaded by the server.
For HttpServlet, service() method dispatches doGet(), doPost() to handle HTTP GET, POST, request
respectively.
The service () method is called by the container which will invokes doGet, doPost, doPut, doDelete,
etc. methods depending on what type of request. So you have to override either doGet() or doPost()
etc. methods
When user submit some form data and that form is using POST method then this type of request is
handled by doPost() method .
public void doPost(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException, IOException {
// Servlet code
}
But mostly a servlet is created by extending HttpServlet abstract class. HttpServlet gives the
definition of service() method of the Servlet interface. The servlet class that we will create will not
override service() method but it will override only doGet() or doPost() method.
When a request comes in for the servlet, the service () method is called by the container which will
invokes doGet, doPost methods depending on what type of request.
Now we will see the steps for writing servlet by extending HttpServlet class using netbeans IDE
which is using apache tomcat as Server.To create a servlet application in Netbeans IDE, you will need
to follow the following steps
Open Netbeans, Select file -> New Project
Select Java Web -> Web Application, then click on next as shown below
4.As you finished the wizard ,you will see WebApp Project directory is created in project tab. To
create a servlet, right click on Source Package -> New -> Servlet as shown below.
5.Give a name to your servlet class file and click on next.On next screen select the check box” Add
information to deployment descriptor(web.xml) and select finish as shown below
6. Above step would create a web.xml file in WEB-INF folder and Format of web.xml file given
below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd">
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
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.
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 provides response for the incoming request. It
request,ServletResponse response) is invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet
is being destroyed.
Example:
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1016";}
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.
Following table lists some of the methods of GenericServlet class.
10 public void log(String msg) Writes the given message in the servlet
log file.
11 public void log(String msg,Throwable t) Writes the explanatory message in the
servlet log file and a stack trace.
Example:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
HTTPSERVLET CLASS
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Following table lists some of the methods of HttpServlet class.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Here you can see that a HelloWorldServlet class is extended from HTTPServlet class and overriding
init(),doGet() and destroy() methods.
To run the file select “HelloworldServlet.java” in Project tab and right click on it and select “Run
File” and you will get following outcome:
To create a form in HTML we need to use some of the HTML tags like:
o <form>: to create a form.
o <input>, <select>, <textarea>…: to create form fields like text boxes, dropdown list, text
area, check boxes, radio buttons,… and submit button.
You need to specify the following attributes for the <form> tag to works with Java servlet.
o method=”post”: to send the form data as an HTTP POST request to the server. Generally,
form submission should be done in HTTP POST method. And the code inside the doPost
method in servlet class will get executed
or
method=”get”:to send the form data as an HTTP GET request to the server and the code
inside the doGet method in servlet class will get executed
o action=”URL of the servlet”: specifies relative URL of the servlet which is responsible for
handling data posted from this form.
Output
Hello <Username entered by user>
Output:
Welcome <username entered by user>
In this as <form Method=GET> so doGet() method of servlet class will called and at the end of this
method we are calling doPost method .So both going to execute and you will get following outcome.
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.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie: It is valid for single session only. It is removed each time when user
closes the browser.
2. 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.
COOKIE CLASS
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.
Example:
Index.html file
<html>
<head>
</head>
<body>
</form>
</body>
</html>
NewServlet.java file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html;charset=UTF-8");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>AK</title>");
out.println("</head>");
out.println("<body>");
String n=request.getParameter("uid");
String v=request.getParameter("pv");
response.addCookie(c);
out.println("cookies added");
c.setMaxAge(60*90);
Cookie c1[]=request.getCookies();
out.println("name="+c1[i].getName());
out.println("value="+c1[i].getValue());
out.println("</body>");
out.println("</html>");
} }}
There are Five different techniques used by Servlet application for session management. These are:
A. User Authentication – This is one of the common way to maintain a session between client and
server. In this method user provides authentication credentials on a login page and then this
authentication information between server and client is used to maintain the session. This is not
very effective method as it wont work if the same user is logged in from different browsers.
B. HTML Hidden Field – we can make some of the fields/ controls to hidden i.e. these are not
visible when the application is viewed in the browser. It acts as a storage area for storing any
page specific information. We can create a unique hidden field in the HTML and when user
starts navigating, we can set its value unique to the user and keep track of the session. This
method can’t be used with links and it’s not secure as one can get the hidden field value from the
HTML source.
C. URL Rewriting – In this method the information in form of string added at the end of the URL
to maintain the state of a web application. Most dynamic sites include string variables in their
URLs that tell the site what information to show the user.This is very tedious because we need to
keep track of this parameter in every response and make sure it’s not clashing with other
parameters.
D. Cookies – Cookies are small piece of information that is sent by web server in response header
and gets stored in the browser cookies. When client make further request, it adds the cookie to
the request header and we can utilize it to keep track of the session. This method would not work
if the client has disables the cookies.
E. Session Management API –Some of programming languages provides APIs for session
tracking. In java the javax.servlet.http package provides HttpSession interface which can be
used to get a sessionid. .An object of HttpSession can be used to view and manipulate
information about a session, such as the session identifier, creation time, and last accessed time.
Request,121 Matching
1. On client's first request, the Web Container generates a unique session ID and gives it back to
the client with response.
2. The client sends back the session ID with each request.
3. The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.
An object that implements HttpSession interface is created by the servlet container and returned when
the getSession () method of HttpServletRequest is called. The HttpSession object provides methods
to read, add, and remove various session data as well as methods to view session information such as
the session identifier, creation time, and the time the session was last accessed. The syntax of
getSession() method is as follows:
A. HttpSession getSession() – This method always returns an object of HttpSession. It returns the
current session associated with this request, if the request has no session attached, then it creates
a new session and return it.
B. HttpSession getSession(boolean flag) – This method returns HttpSession object if request has
session else it returns null.
</form>
</body>
</html>