Unit - II Servlet
Unit - II Servlet
1>standard for writing programs that can interact through a Web server with a client running a Web browser.
2>programs allow a Web developer to deliver dynamic information (usually in the form of HTML) via the browser.
3> middle man type interface thorough which web servers pass user’s requests to external databases and receive
Introduction to CGI:-
The Common Gateway Interface (CGI) is a standard for writing programs that can
interact through a Web server with a client running a Web browser.
These programs allow a Web developer to deliver dynamic information (usually in the
form of HTML) via the browser.
Common Gateway Interface (CGI) is middle man type interface thorough which web
servers pass user’s requests to external databases/ information resources/ program
applications and receive the processed data to send it back to user.
Common Gateway Interface (CGI) programs run on the server and generate a response
to return to the requesting client.
CGI is a standard method used to generate dynamic content on web pages.
CGI programs can be written in the C, C++, Java, and Perl languages, and as shell
scripts.
It is an API for writing applications (often scripts) that can be run by a web server to
service a particular range of URLs.
It allows users to execute a program that resides in the server to process data and
even access database in order to produce the relevant content as shown in fig.
PERFOR 2. Performance :-
Servlet provide better performance that CGI in terms of processing time, memory
utilization because servlets uses benefits of multithreading and for each request a new
thread is created, that is faster than loading creating new Object for each request
with CGI.
EXTENS 3. Extensibility :-
Java Servlets are developed in java which is robust, well-designed and object oriented
language which can be extended or polymorphed into new objects. So the java servlets
take all these advantages and can be extended from existing class to provide the ideal
solutions.
4. Safety :-
SAFTY
Java provides very good safety features like memory management, exception handling
etc. Servlets inherits all these features and emerged as a very powerful web server
extension.
SECURITY 5. Secure :-
Servlets are server side components, so it inherits the security provided by the web
server. Servlets are also benefited with Java Security Manager.
Servlets can handle the cookies. CGI cannot handle the cookies.
Cookies handling
Features of Servlet
Following are the main features of servlet:-
1. Portable:
Servlet uses Java as a programming language, Since java is platform independent,
the same holds true for servlets. For example, you can create a servlet on
Windows operating system that users GlassFish as web server and later run it on
any other operating system like Unix, Linux with Apache tomcat web server, this
feature makes servlet portable and this is the main advantage servlet has over
CGI.
2. Efficient and scalable:
Once a servlet is deployed and loaded on a web server, it can instantly start
fulfilling request of clients. The web server invokes servlet using a lightweight
thread so multiple client requests can be fulling by servlet at the same time using
the multithreading feature of Java. Compared to CGI where the server has to
initiate a new process for every client request, the servlet is truly efficient and
scalable.
3. Robust:
By inheriting the top features of Java (such as Garbage collection, Exception
handling, Java Security Manager etc.) the servlet is less prone to memory
Servlets Packages:
There are two types of packages in Java Servlet that are providing various functioning
features to servlet Applications. The two packages are as follows:
1. javax.servlet package
2. javax.servlet.http package
1. javax.servlet package :-
This package of Servlet contains many servlet interfaces and classes which are capacity
of handling any types of protocols And This javax.servlet package containing large
interfaces and classes that are invoked by the servlet or web server container as they are
not specified with any protocol.
Important Classes and Interfaces of javax.servlet package:
Interfaces Classes
Servlet GenericServlet
ServletConfig HttpConstraintElement
ServletContext HttpMethodConstraintElement
ServletContextListner MultipartConfigElement
ServletRegistration ServletContextEvent
ServletRequest ServletInputStream
ServletRequestListner ServletOutputStream
ServletResponse ServletRequestAttributeEvent
ServletCookieConfig ServletRequestEvent
SingleThreadModel ServletRequestEvent
Filter ServletRequestWrapper
FilterChain ServletSecurityElement
Interface Overview
Classes Overview
ServletInputStream This class is used to read the binary data from user
requests.
ServletOutputStream This class is used to send binary data to the user side.
Interfaces Classes
HttpServletRequest Cookie
HttpServletResponse HttpServlet
HttpSession HttpServletRequestWrapper
HttpSessionActivationListner HttpServletResponseWrapper
HttpSessionContext HttpSessionBindingEvent
HttpSessionAttributeListner HttpSessionEvent
HttpSessionIdListner HttpUtils
Interface Overview
HttpServletRequest The object of this interface is used to get the information from
the user under http protocol.
Class Overview
HttpSessionEvent This class notifies if any changes occur in the session of web
application.
webserver call The service() method is the main method to perform the actual task.
service() The servlet container (i.e. web server) calls the service() method to handlerequests
when request come coming from the client( browsers) and to write the formatted response back to the
client.
service() check http Each time the server receives a request for a servlet, the server spawns a new
request type thread and calls service.
(GET,POST,PUT,
The service() method checks the HTTP request type (GET, POST, PUT,
DELETE)
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
and call (doGET,
doPOST, appropriate.
doPUT, Here is the signature of this method:
doDELETE)
Public void service(ServletRequest request,ServletResponse
response) throws ServletException,IOException
{
//servlet code here
}
The service () method is called by the container and service method invokes
doGet, 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.
Types of Servlet:-
1) Generic servlets:
o Extend javax.servlet.GenericServlet.
o Contain no inherent HTTP support or any other transport protocol, so that
protocol is independent.
2) HTTP servlets:
o Extend javax.servlet.HttpServlet.
o Contain built-in HTTP protocol support and are more useful in a Sun Java
System Web Server 7.0 environment.
1) GenericServlet Class :-
GenericServlet implements the Servlet interface and provides an implementation
for all its method except the service() method.
Hence it is abstract.
GenericServlet class defines a protocol-independent(HTTP-less) servlet.
Developing Servlet by extending GenericServlet is very easy because we have to
provide implementation only for the service() method.
GenericServlet class is in javax.servlet package (javax.servlet.GenericServlet).
service() method-
The prototype of service( ) method is :
public void service (ServletRequest req, ServletResponse resp) throws
ServletException,IOException
index.html
We are creating an html file that would call the servlet once we click on the link on web page.
Create this file in WebContent folder. This path of the file should look like this:
WebContent/index.html
<!DOCTYPE html>
<html>
<head>
Now, we are creating a Generic Servlet by extending GenericServlet class. When creating a
GenericServlet you should always override service() method.
HelloWorld.java
import java.io.*;
import javax.servlet.*;
{
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println("Hello Servlet");
pw.close();
}
}
MyServlet1.java
import java.io.*;
import javax.servlet.*;
Program 3 :-
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
2) 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.
The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace.
For instance, the doGet method is invoked when the servlet receives an a HTTP request
that was send using the GET method.
Among these methods, the doPost and doGet methods are the most frequently used.
Methods in HttpServlet :-
The methods in httpservlet are given as follows:
1. protected void doDelete (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle a DELETE
request. The DELETE operation allows a client to remove a document or web page from
the server.
2. protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws
ServletException, IOException
Called by the server (via the service method)”to allow a servlet to handle a GET request.
Overriding this method to support a GETrequest also automatically supports an HTTP
HEAD request.
3. protected void doHead(HttpServletRequest req,HttpServletResponse resp)
throws ServletException, IOException
Receives an HTTP HEAD request from the protected service method and handles the
request.
4. protected void doOptions(HttpServletRequest req,HttpServletResponse resp)
throws ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle OPTIONS
request. The OPTIONS request determines which HTTP methods the server supports and
returns an appropriate header.
5. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle a POST request.
The HTTP POST method allows the client to send data of unlimited length to the Web
server a single time and is useful when posting information such as credit card numbers.
6. protected void doPut(HttpServletRequest req,HttpServletResponse resp) throws
ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle a PUT request.
The PUT operation allows a client to place a file on the server and is similar to sending a
file by FTP.
7. protected void doTrace(HttpServletRequest req,HttpServletResponse resp) throws
ServletException, IOException
Program 1:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
} // class ends
Program 2:-
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
The diagram above depicts how to arrange the Servlet files in a specific directory
structure, as per Java Servlet Specification-
Project Folder - We have created a new folder for this project named GenericServ
within the Tomcat webapps folder, which contains our Servlet class(.java) file.
WEB-INF - This folder should contain the deployment descriptor file(web.xml) of
your Java Servlet program.
classes - This folder should contain the compiled(.class) form of your Java Servlet
class.
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examp*les/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorGetServlet.java is shown in the following listing. The
doGet() method is overridden to process any HTTP GET requests that are sent to this
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Compile the servlet and perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the Web page in a browser.
3. Select a color.
4. Submit the Web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL
that is sent to the Web server. Assume that the user selects the red option and submits the
form.
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/examples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorPostServlet.java is shown in the following listing. The
doPost( ) method is overridden to process any HTTP POST requests that are sent to this
servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection
that was made by the user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
Compile the servlet and perform the same steps as described in the previous section to
test it.
GET POST
5) Get request is more efficient and Post request is less efficient and
EFFICIENCY
used more than Post. used less than get.
1) Forword () Method:-
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.
The response of second servlet is sent to the client. Response of the first servlet is
not displayed to the user.
1) Forword () Method:-
1.Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
2.The response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GFG extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
{
// Perform all the work as per your
// application's architecture
try {
RequestDispatcher requestDispatcher;
// path is a string specifying the pathname to
// the resource. If it is relative, it must be
// relative against the current servlet
requestDispatcher = request.getRequestDispatcher("path");
requestDispatcher.forward(request, response);
}
catch (ServletException servletException) {
}
catch (IOException ioException) {
}
catch (IllegalStateException illegalStateException) {
}
}
2) Include () Method:-
Includes the content of a resource (servlet, JSP page, or HTML file) in theresponse.
Response of second servlet is included in the response of the first servlet that is
being sent to the client.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GFG extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
{
// Perform all the work as
// per your application's architecture
try {
RequestDispatcher requestDispatcher;
// path is a string specifying the pathname to
}
}
}
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("Paniv"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Output:-
When Entering User name or password incorrect.
A. Cookies
Cookies are little pieces of data delivered by the web server in the response header and kept
by the browser. Each web client can be assigned a unique session ID by a web server.
Cookies are used to keep the session going. Cookies can be turned off by the client.
1> little pieces of data delivered by the web server in the response header and kept by the browser
2> Each web client can be assigned a unique session ID by a web server.
3>used to keep the session going
4>Cookies can be turned off by the client.
With each request and return, append some more data via URL as request parameters. URL
rewriting is a better technique to keep session management and browser operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is established between an
HTTP client and an HTTP server using the HttpSession interface. A user session is a
collection
1> small piece of data about
of information as a atext
userfile
that spans on
stored many HTTPmachine
client’s requests.by a web application.
2> kept for various information tracking purpose.
3> Servlets transparently supports HTTP cookies
4> HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every
1) Cookies :-
new request
5> case of cookie
A a cookie
text fileiswith small
a small piece
piece of information
of information is added
as a text to the
file stored onresponse of first by
client’s machine request.
a
6> when a new request comes
web application. cookie is by default added with the request
7> With this information we can identify that it is a new user or a previous user.
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose.
Java Servlets transparently supports HTTP cookies.
As HTTP is a stateless protocol so there is no way to identify that it is a new user or
previous user for every new request.
In case of cookie a text file with small piece of information is added to the response of
first request.
They are stored on client’s machine.
Now when a new request comes cookie is by default added with the request.
With this information we can identify that it is a new user or a previous user.
Types of cookies:
1. Session cookies/Non-persistent cookies: These types of cookies are session
dependent i.e. they are accessible as long as session is open and they are lost when
session is closed by exiting from the web application.
2. Permanent cookies/Persistent cookies: These types of cookies are session
independent i.e. they are not lost when session is closed by exiting from the web
application. They are lost when they expire.
Cookie class :-
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot
of useful methods for cookies.
Constructor Description
There are given some commonly used methods of the Cookie class.
Method Description
public String getName() Returns the name of the cookie. The name
cannot be changed after creation.
Advantages of cookies:
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
DISADVANTAGES:-
1. if cookie is disabled from the browser.
Disadvantages of cookies: 2.Only textual information
3.SEQURITY RISK
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</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>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Here, Paniv is the hidden field name and SIIT is the hidden field value.
Index.html
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="Post">
<!-- Move the control to firstServlet -->
Name:<input type="text" name="userName" /><br />
<input type="submit" value="submit" />
</form>
</body>
</html>
Output
FirstServlet.java
// Java program to demonstrate
// Hidden form field method
package GeeksforGeeks;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/FirstServlet")
String username =
request.getParameter("userName");
out.print("Welcome " + username);
out.print("<form action='SecondServlet'>");
out.print("<input type='hidden' name='username' value='"
+ username + "'>");
out.print("<input type='submit' value='submit'>");
out.print("</form>");
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output
SecondServlet
// Java program to demonstrate
// Hidden form field method
package GeeksforGeeks;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet; // Importing annotation
import javax.servlet.http.*;
catch (Exception e) {
System.out.println(e);
}
}
}
Output
3) URL Rewriting :-
URL rewriting is the process of modifying Uniform Resource Locators (URLs) for
various purposes.
The URL as a “web address” is a string that, when entered into the browser bar field,
directs the browser to move to a given site and page.
Changing the URL can help with user access and site visibility; it can also be used by
hackers to redirect users without their knowledge or “trap” them in a certain site.
SYNTAX- URL rewriting is a way of appending data at the end of URL. Data is appended in name
url?name1=value1&name2=value2&??
<<DESCRIBE IT >> value pair form. Multiple parameters can be appended in one URL with name value
pairs.
We can send parameter name/value pairs using the following format:
Syntax:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand(&).
When the user clicks the hyperlink, the parameter name/value pairs will be passed to the
server.
From a Servlet, we can use getParameter() method to obtain a parameter value.
In this example, we are maintaining the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query string
in another page.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</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>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
4) HttpSession:-
HttpSession is an interface that provides a way to identify a user in multiple page
requests.
A unique session id is given to the user when first request comes. This id is stored in
a request parameter or in a cookie.
1>Any kind of object can be stored into a session, be it a text, database, dataset etc.
2>Usage of sessions is not dependent on the client’s browser.
3>
Advantages of Http Sessions in Servlet
Any kind of object can be stored into a session, be it a text, database, dataset etc.
Usage of sessions is not dependent on the client’s browser.
Sessions are secure and transparent.
index.html
<html>
<head>
<body>
<form action="servlet1">
First.java
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
/*Fetching the contents of the userName field from the
form*/
out.print("Welcome " + n); // Printing the username
session.setAttribute("uname", n);
out.print("<a href='servlet2'>visit</a>");
// Link to the second servlet
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
String n = (String)session.getAttribute("uname");
out.print("Hello " + n);
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>First</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>Second</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
index.html :
Servlet1 :
Servlet2 :