You are on page 1of 112

Prepared By

A.Kiran Kumar
Asst Prof
CMRTC
CSE Dept
UNIT – III
Introduction to Servlets: Common Gateway Interface (CGI), Life cycle of a Servlet,
deploying a servlet, The Servlet API, Reading Servlet parameters, Reading Initialization
parameters, Handling Http Request & Responses, Using Cookies and Sessions,
connecting to a database using JDBC.
CGI: Common Gateway Interface

• CGI is an external application that is written by using any of the programming languages
like C, C++, Perl, PHP, and Python and this is responsible for processing client requests
and generating dynamic content.

• For each request, it starts a new process.

• CGI stands for Common Gateway Interface and provides an interface between the HTTP
Server and programs generating web content.

• CGI (Common Gateway Interface) is used for server-side programming

• known as or simply as

• CGI is used for simple interactive applications.

• CGI are reusable pieces of code.

• HTML pages consist of forms, which use CGI programs to process the data available in
forms.
In CGI application, when a client makes a request to access dynamic Web pages, the Web
server performs the following operations :
•It first locates the requested web page the required CGI application using URL.
•It then creates a new process to service the client’s request.
•Invokes the CGI application within the process and passes the request information to the
application.
•Collects the response from the CGI application.
•Destroys the process, prepares the HTTP response, and sends it to the client.
Advantages of CGI:
•They are language-independent so it makes it easier for any programmer to choose their
preferred language.
Ex: C , C++, Perl ,PHP, and Python :
•They are very simple and can do advanced tasks much easier than other server-side
programming languages.
•There is a huge existing CGI code library that can be reused.
•They are secure as they run on the web server.
•They are very lightweight as no specific library is needed to be present in order for the
code to execute.
Disadvantages of CGI
There are many problems in CGI technology:
1.If the number of clients increases, it takes more time for sending the response.
2.For each request, it starts a process, and the web server is limited to start processes.
3.It uses platform dependent language e.g. C, C++, perl.
5.No separation of presentation and business logic.

6.CGI is more expensive than Servlets.

7.CGI is not portable


Servlet:
Servlet Definition:
Servlet is a java program executed in a web container of a web server. It is used for
developing dynamic web applications.
• Servlet is a class that handles requests, processes them and reply back with a
response.
• For example, we can use a Servlet to collect input from a user through an HTML form,
query records from a database, and create web pages dynamically.
• Servlet is an API that provides many interfaces and classes such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.
• Servlets works on the server side
• Servlet’s main purpose to serve the client’s request hence the name servlet.
Web Container: Also known as Servlet Container and Servlet Engine. It is a part of Web
Server that interacts with Servlets. This is the main component of Web Server that
manages the life cycle of Servlets.
Web Server: It is also known as HTTP Server, it can handle HTTP Requests send by client
and responds the request with an HTTP Response.
Web Client:The web browser acts as a Client. Client or user connected with a web browser.
The client is responsible for sending requests or HttpRequest to the web server and
processing the Web server’s responses.
The advantages of Servlet Over CGI:
1.Better performance: It creates a thread for each request, not process.
2.Portability: Servlet uses Java Since java is platform-independent. So Servlet programs
are portable.
Ex: you can create a servlet on Windows operating system that uses GlassFish as the web
server and later run it on any other operating system like Unix, or Linux with Apache
tomcat web server
3. Robust: Servlets are managed by JVM so no need to worry about memory leaks,
garbage collection etc.
4. Secure: Because it uses java language. It enables us to develop virus-free, temper-free
programs.
5. Efficient and Scalable: Once a servlet is deployed and loaded on a web server, it can
instantly start fulfilling the requests of clients.
6. Expensive: Servlets are less expensive than CGI.
Servlet Features
1.Better performance: It creates a thread for each request, not process.
2.Portability: Servlet uses Java , Since java is platform independent.So Servlet programs
are portable.
3.Robust: Servlet are managed by JVM so no need to worry about memory leak, garbage
collection etc.
4.Secure: Because it uses java language . It enable us to develop virus free, temper free
programs.
5.Efficient and Scalable: Once a servlet is deployed and loaded on a web server, it can
instantly start fulfilling request of clients.
6.Inexpensive There are number of free web servers available for personal use or for
commercial purpose. So by using free web server you can reduce project development
price.
7.Extensibility :The servlet API is designed in such a way that it can be easily extensible.
8.Persistent: Servlets remain in memory until explicitly destroyed. Servlets establishes
connection only once with the database and can handle several requests on the same
database.
9.Fast: Since servlets are compiled into bytecodes, they can execute more quickly as
compared to other scripting languages
10.Protocol Independent: Servlets can be created to support any protocols like FTP, HTTP
and SMTP protocol.
Servlet Architecture or How servlet works
Steps how servlet works
1.The clients send the request to the webserver.
2.The web server receives the request.
3.The web server passes the request to the corresponding servlet.
4.The servlet processes the request and generates the response in the form of output.
5.The servlet sends the response back to the webserver.
6.The web server sends the response back to the client and the client browser displays it
on the screen.
Servlet Life cycle:
A servlet life cycle can be defined as the entire process from its creation till the
destruction.
Life cycle of a servlet is managed by web container.
Servlet life cycle steps:
1.Load Servlet Class.
2.Create Servlet instance.
3.Call init() method.
4.Call service() method.
5.Call destoy() method.

1. Load Servlet Class: Web container loads the servlet when the first request is received.
This step is executed only once at the time of first request.
2. Servlet instance creation :After the Servlet class is loaded, Web Container creates the
instance of it. Servlet instance is created only once in the life cycle.
3. Call init() method: After creating the servlet instance web container calls the servlet’s
init() method to initialize the servlet before processing the first request.
It is called only once by the web container.
Ex: public void init(ServletConfig config) throws ServletException
4. Call service() method: After the initialization process web container calls the service
method. The service method is called for every request. We write business logic inside the
service method.
Ex: public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5. Call to destroy() method: The Web Container call the destroy() method before removing
the servlet instance,
giving it a chance for cleanup activity.
Ex: public void destroy()
Servlet Life Cycle
Web.xml in Servlet
It is a web application deployment descriptor file, contains detail description about web
application like configuration of Servlet, Session management, Startup parameters,
Welcome file..etc.
We can not change the directory or extension name of this web.xml because it is
standard name to recognized by container at run-time.
web.xml is present inside the Web-INF folder.
The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are
many xml parsers such as SAX, DOM and Pull.
Description of the elements of web.xml file
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to
invoke the servlet.
How to deploy a Servlet
Deployment Steps to Create Servlet Application using tomcat server

1.Create a directory structure


2.Create a Servlet
3.Compile the Servlet
4.Create a deployment descriptor
5.Start the server and deploy the project
6.Access the servlet
1)Create a directory structures
The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.
servlet class file must be in the classes folder. The web.xml file must be under the
WEB-INF folder.
2)Create a Servlet
There are three ways to create the servlet.
By implementing the Servlet interface
By inheriting the GenericServlet class
By inheriting the HttpServlet class
The HttpServlet class is widely used to create the servlet because it provides methods to
handle http requests such as doGet(), doPost, doHead() etc.

In this Example Iam creating the Servlet using Generic Servlet


create the Servlet by extending the Generic Servlet

Ex: First.java
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
Step3: Create the deployment descriptor file (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>/hello</url-pattern>
</servlet-mapping>
</web-app>
Step3: Compile the Servlet
3.Compile the servlet
For compiling the Servlet, jar file is required to be loaded.
servlet-api.jar Apache Tomcat load the jar file
two ways to load the jar file
1.set classpath
2.paste the jar file in JRE/lib/ext folder
1.set classpath
C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\
first Application\WEB-INF\classes > set classpath=.;C:\Program Files\Apache Software
Foundation\Tomcat 7.0\lib\servlet-api.jar
press enter
compile the servlet
C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\first
Application\WEB-INF\classes >javac DemoServlet.java
4. Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.
5)Start the Server and deploy the project
To start Apache Tomcat server, double click on the tomcat7.exe file under
apache-tomcat/bin directory.
6) How to access the servlet
Open any browser then type the URL:

http://localhost:8085/webapp/MyFirst/First

You will get the output


Servlet API
• Servlet API provides Classes and Interface to develop web applications.
• To create Java Servlets, we need to use Servlet API which contains all the necessary
interfaces and classes
• Servlet API consists of two important packages which contains all necessary classes
and interface are used to develop the servlet programs they are
1.javax.servlet
2.javax.servlet.http
1.javax.servlet
The javax.servlet package contains many interfaces and classes to develop servlets
irrespective of any protocol.
It support generic servlet (protocol-independent servlet).
These are not specific to any protocol.
2.javax.servlet.http
The javax.servlet.http package contains interfaces and classes to develop http servlets.
it is responsible for http requests only.
The javax.servlet package contains many interfaces and classes. Some of the interfaces
and and classes are listed in table.
Interfaces Description

Servlet Declares life cycle methods that all servlets must implement.

ServletConfig Allows servlets to get initialization parameters

ServletContext Allows servlets to communicate with its servlet container.

ServletRequest Provides client request information to a servlet.

ServletResponse Assist a servlet in sending a response to the client.

Classes Description

GenericServlet Provides a basic implementation of the Servlet interface


for protocol independent servlets
ServletlnputStream Provides an input stream for reading binary data from a client request.

ServletOutputStream Provides an output stream for sending binary data to the client.

ServletException Defines a general exception, a servlet can throw when it encounters


difficulty.
Interfaces of javax.servlet package
1.servlet:
Every servlet in java should implement a servlet interface directly or indirectly
by extending either the GenericServlet or HttpServlet class.
It provides 3 life cycle methods and 2 non-life cycle methods.
1. public void init(ServletConfig config): It is called to initialize the Servlet.
2. Public void service(ServletRequest request, ServletResponse response): It provides a
response for the incoming request.We can write application login in service method to
process a request
3. Public void destroys (): It destroys the Servlet.
4.Public ServletConfig getServletConfig():It returns the object of ServletConfig.
5. Public String getServletInfo(): It returns a String object containing information about the
servlet such as Author, creation date, version, copyright, etc.
2. ServletRequest:
The ServletRequest interface defines an object that encapsulates information about
a single client request.
some of the methods of ServletRequest Interface are
1.getparameter (String name): It returns the value of the specified parameter.
2.getContentType(): It return MIME type of body of request.
3.getParameterNames():It returns an enumeration of all parameter names.
4.getServletContext() : It return the servlet context of current request.
3.ServletResponse:
The ServletResponse interface defines an object that can be used to prepare and send
response to the client.
The servlet container create a ServIetResponse object and passes it as an argument to
the servlet’s service () method.
some of the methods of ServletResponse Interface are
1.setContentType(String type): It sets the MIME type of the response being sent to the
client.
2.getWriter(): It returns a PrintWriter object that can send character text in the response.
4.ServletContext:
For every Web application a ServletContext object is created by the web container.
ServletContext object is used to get application level configuration information
like name of the application and ServletContext from
Deployment Descriptor(web.xml) which will be available to any servlet or JSPs
Note: ServletConfig is per Servlet
ServletContext is per web app
Methods of ServletContext interface are:
1.getInitParameter(String name): It returns parameter value for the specified parameter
name
2.getInitParameterNames(): It returns the names of the context's initialization parameters
5.ServletConfig:
For every servlet, webcontainer creates one ServletConfig object to hold its configuration
information like the logical name of the Servlet,
Instantiation parameters etc.
ServletConfig interface defines several methods to access servlets configuration
information.
The ServletConfig object is used to pass information to a servlet during initialization by
getting configuration information from web.xml(Deployment Descriptor).
Methods :
1.getInitParameter(String name): It returns a String value initialized parameter.
2.getServletName():It returns the name of the servlet instance.
3. getServletContext():Returns an object of ServletContext.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if the
information is modified from the web.xml file.
•We could create a Servlet in various ways –
•By implementing the Servlet interface.
•By extending GenericServlet abstract class.
•By extending HttpServlet class.

1. By implementing servlet interface


public class myServlet implements Servlet
{
.......
.......
}
Ex1 create servlet by implementing the Servlet interface.
Step1: create the Servlet with the name First.java
import java.io.*;
import javax.servlet.*;
public class First implements Servlet
{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res) throws
IOException,ServletException{
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-1010";}
}
Step2: Create the deployment descriptor file (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>/hello</url-pattern>
</servlet-mapping>
</web-app>
Step4: compile the servlet
C:\Program Files\Apache Software Foundation\Tomcat
7.0\webapps\servvletex\WEB-INF\classes>javac First.java
Step5: Deploy the Servlet in Tomcat server and start the tomcatserver
Step6: open the browser and type
http://localhost:8082/servvletex/hello

You get the output:


Generic Servlet
GenericServlet class Implements Servlet, ServletConfig, and Serializable Interfaces.
• It provides the implementation of all the methods of these Interfaces except the service
method.
• A generic servlet is a protocol-independent Servlet that should always override the
service() method to handle the client request.
• GenericServlet class can handle any type of request so it is protocol Independent.
• GenericServlet is an abstract class that
implements Servlet and ServletConfig interface.
• You may create a generic Servlet by inheriting the GenericServlet class and providing
the Implementation of the service method.

Note: if we are defining our servlet by extending Generic servlet no need to define all
methods .we need to define only one method i.e service (request, response)
By extending GenericServlet class
Example
public class myServlet extends GenericServlet
{
.......
.......
}
Methods of Generic Servlet
1. init(ServletConfig config) It is used to initialize the servlet.

2. void service(ServletRequest request, ServletResponse response) It provides service


for the incoming request.

3. public void destroy() :It destroys the servlet

4. getServletConfig() It returns the object of ServletConfig.

5. getServletInfo() It returns information about servlet such as writer, copyright, version

6. getServletContext() It returns the object of ServletContext.

7. getInitParameter(String name):It returns the parameter value for the given parameter
name.

8. getInitParameterNames():It returns all the parameters defined in the web.xml file.

9. String getServletName() :It returns the name of the servlet object.


Ex create the Servlet by extending the Generic Servlet
Step1: create the servlet with the name First.java
Ex: First.java
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
Step2: Create the deployment descriptor file (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>/hello</url-pattern>
</servlet-mapping>
</web-app>
Step3: Compile the Servlet
Step4: compile the servlet
C:\Program Files\Apache Software Foundation\Tomcat
7.0\webapps\servvletex\WEB-INF\classes>javac First.java
Step5: Deploy the Servlet in Tomcat server and start the tomcatserver
Step6: open the browser and type
http://localhost:8082/servvletex/hello

You get the output:


Hello Generic Servlet
HttpServlet
An HTTP servlet is a special type of servlet that handles an HTTP request and provides an
HTTP response, usually in the form of an HTML page.
HttpServlet is an abstract class, it comes under package ‘javax.servlet.http.HttpServlet‘ .
The HttpServlet class extends the GenericServlet class and implements a Serializable
interface.
• HttpServlet methods allow us to handle any sort of HTTP request made by the user,
whether it’s , etc by providing appropriate methods to handle each
of these HTTP requests.
• The mostly used approach is by extending HttpServlet because it provides HTTP
request-specific methods such as doGet(), doPost(), doHead(), etc.
• HttpServlet is protocol-dependent and used specific to HTTP protocol only.
Interfaces in javax.servlet.http package

HttpServletResponse interface: It is used to enable servlets to write data to an HTTP


response.
HttpServletRequest interface: It is used to enable servlets to read data from an HTTP
request.
HttpSession interface: It allows session data to be read and written.

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:

HttpServlet class: It provides methods to handle HTTP requests and responses.


Cookie class: It is used to store state information on a client system.
HttpSessionEvent class: It is used to wrap a session changed event
Methods of HttpServlet class
1.public void service(ServletRequest req, ServletResponse res) dispatches the request to
the protected service method by converting the request and response object into HTTP
type.
2.protected void service(HttpServletRequest req, HttpServletResponse res) receives the
request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3.protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET
request. It is invoked by the web container.
4.protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request.
5.protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the
HEAD request.
6.protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the
OPTIONS request.
7.protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the
DELETE request..
8.protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT
request.
9.protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the
TRACE request.
Handling Http Request & Responses
HttpServletRequest
• It is used to enable servlets to read data from an HTTP request.
• The HttpServlet class provides specialized methods that handle the various types of HTTP
requests. A servlet developer typically overrides one of these methods.
• These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ),
and doTrace( ).
• IF you can send data using POST or GET request by explicitly specifying method
parameter for the form tag like this :
Ex:
<form method="POST" action="">
<form method=“GET" action="">
Methods of HttpRequest
1.void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET
request.The GET method is used to retrieve information from the given server using a
given URI.
2.doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. A
Post method is used to send data to the server.
3. doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request.
Same as GET, but it transfers the status line and the header section only.
4. doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS
request.
5. doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request.
6. doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request.The
Put method is used to update resources available on the server.
7. doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request.
A TRACE returns the headers sent with the TRACE request to the client.
HttpServletResponse :
• It is used to enable servlets to write data to an HTTP response.
Methods of HTTP Response
• void setContetType(String type):Sets the content type of the response being sent to
the client
• void sendRedirect(String location):Sends a temporary redirect response to the client
using the specified redirect location URL.
• void addCookie(Cookie cookie):Adds the specified cookie to the response.

• void addHeader(String name, String value):Adds a response header with the given
name and value.
• void reset():Clears any data that exists in the buffer as well as the status code and
headers.
•doGet():
•The doGet() method in servlets is used to process the HTTP GET requests.
•the GET method is used to send data from the browser to the server
•The data that is being submitted to the server will be visible in the URL using query
parameters like this “ ”.
•So, if you are sending any sensitive information like passwords, you should not use the
GET method as the data entered can be clearly visible in the browser URL.
•In case of Get request, only limited amount of data can be sent because data is sent in
header.

•doPost()
•The doPost() method in servlets is used to process the HTTP POST requests.
•It is used to submit the data from the browser to the server for processing.
•In case of post request, large amount of data can be sent because data is sent in body.
•The data submitted with POST method type is sent in the message body so it is secure
and cannot be seen in the URL.
•Sensitive data can be send by using POST method.
Handling HTTP GET Requests
Create a servlet that handles an HTTP GET request

home.html

<html>

<form action="./s1" method =”Get”>

<br> Enter First Number1:<input type="text" name="n1"/>

<br>Enter Second Number:<input type="text" name="n2"/>

<br> <input type="submit" value="submit">

</form>

</html>
AddServlet.java

import java.io.*;

import javax.servlet.http.HttpServlet.*;

public class AddServlet extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {

response.setContentType("text/html");

String s1=request.getParameter("n1");

String s2=request.getParameter("n2");

int a=Integer.parseInt(s1);

int b=Integer.parseInt(s2)

int c=a+b;

PrintWriter out=response.getWriter();

out.println("<h1> sum="+c); out.close(); } }


web.xml

<web-app>

<servlet>

<servlet-name>ser1</servlet-name>

<servlet-class>AddServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ser1</servlet-name>

<url-pattern>/s1</url-pattern>

</servlet-mapping>

</web-app>
Handling HTTP POST Requests
Create a servlet that handles an HTTP POST
Login.html
<html>
<head>
<title>Welcome To Login</title>
</head>
<body>
<center>
<form method="post" action="Log">
Name:<input type="text" name="name" /><br/><br/
Password:<input type="text" name="password" /><br/><br/>
<input type="submit" value="Login" /><br/>
</form>
</center>
</body>
</html
Login.java

Login.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class Login extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
PrintWriter out = res.getWriter();
String name= req.getParameter(“name”);
String password= req.getParameter(“password”);
out.println(“Your login ID is: “);
out.println(name);
out.println(“Your password is: “);
out.println(password);
out.close();
}
Web.xml
<web-app>
<servlet>
<servlet-name>Log</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Log</servlet-name>
<url-pattern>/Log</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Reading Servlet parameters
• Servlet parameters are key-value pairs created by the browser, stored in the request
message and send to the server servlet.
• In some cases the servlet must take input from the browser to process the request and
to send a desired response.
• A browser can send this input to servlet by using servlet parameters or request
parameters.

• The ServletRequest interface includes methods that allow you to read the names and
values of parameters that are included in a client request.

• To gthe et request parameter value we use the following method

request.getParameter(“parametername”);
ServletRequest interface methods to read servlet parameters
Servlets handles form data parsing automatically using the following methods
depending on the situation −
•getParameter() − You call request.getParameter() method to get the value of a form
parameter.
•getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
•getParameterNames() − Call this method if you want a complete list of all parameters in
the current request.
Write a servlet program to Read servlet parameters
home.html

<html>

<form action="./s1">

<br> Enter First number:<input type="text" name="n1"/>

<br> Enter Second number:<input type="text" name="n2"/>

<br> <input type="submit" value="add">

</form>

</html>
AddServlet.java

import javax.servlet.*;

import java.io.*;

public class AddServlet extends GenericServlet

public void service(ServletRequest request,ServletResponse response) throws


IOException

response.setContentType("text/html");

String s1=request.getParameter("n1");

String s2=request.getParameter("n2");
int a=Integer.parseInt(s1);

int b=Integer.parseInt(s2);

int c=a+b;

PrintWriter out=response.getWriter();

out.println("<h1> sum="+c);

out.close();

}
Reading Initialization parameters
• some times servlet need initialization data which is not given by the client or browser
then how to supply this initialization data to the servlet .
• Using a new concept called “Initialization parameters” or Servlet config parameters
Initialization parameters
The parameters with name and values are configured in web.xml inside servlet
configuration are called initalization parameters.
• Initialization parameters are stored as key value pairs. They are included
in file inside tags.
• The key is specified using the tags and value is specified using
the tags.
• Servlet initialization parameters are retrieved by using the object.
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.
<web-app>
<servlet>
......

<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>
Following methods in interface can be used to retrieve the initialization
parameters:

•String getInitParameter(String parameter_name): It is used to read the init parameter


values
•Enumeration getInitParameterNames(): It is used to return the init parameter names.
Write a servlet program to read initialization parameters fom web.xml by
ReadInitParam.java
import javax.servlet.ServletConfig;
import javax.servlet.http.*;
import java.io.*;
public class ReadInitParam extends HttpServlet
{
public void service( HttpServletRequest req, HttpServletResponse res ) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
ServletConfig config = getServletConfig();
String cn=config.getInitParameter(“a”);

pw.println("<br> Reading init parameters a=”+cn);

pw.close();

}
web.xml

<web-app><servlet>

<init-param>

<param-name>a</param-name>

<param-value> 2</param-value>

</init-param>

<servlet-name>ser1</servlet-name>

<servlet-class> ReadInitParam </servlet-class> Output: Reading init parameters=2

</servlet>

<servlet-mapping>

<servlet-name>ser1</servlet-name>

<url-pattern>/s1</url-pattern>

</servlet-mapping> </web-app>
Session Tracking in Servlets
• 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:
1.Cookies
2.HttpSession
3.Hidden Form Field
4.URL Rewriting
Cookies:
• cookie is a small piece of data stored on the client-side which servers use when
communicating with clients.
• 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.
• Cookies are created using Cookie class present in Servlet API.
• Cookies are used to identify a client when sending a subsequent request.
• It is one of the state management techniques in session tracking.
• It is a class in javax.servlet.http package
• The cookies are introduced by net scape communication.
•Cookies files exist up to 3 year.
•We can store 3000 cookies in cookies file at a time.
•Size of cookies is 4 kb.
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.

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
1.Simplest technique of maintaining the state.
2. Cookies are maintained on the client side so they do not give any burden to the server.
3. Reduced network traffic as compared to URL rewriting.
4. Reduced the application logic complexity.
5. All server-side technology and all web servers, and application servers support cookies.
Disadvantage of Cookies
1.It will not work if the cookie is disabled from the browser.
2.Only textual information can be set in the Cookie object.
3. Cookies are not secured
How to create a Cookie?
Syntax:
Cookie c=new Cookie(name, value);
Cookie ck=new Cookie("user","cherry");//creating cookie object
How to add Cookies
To add a cookie to the response object, we use addCookie() method.
Cookie c1=new Cookie(“user”, ”cherry”); //creating cookie object
response.addCookie(c1); //adding cookie in the response
Read Cookies for browser or How to Get Cookies
To read Cookies from the browser to a servlet, we need to call getCookie() given by the
request object and it returns an array type of cookie class.
Ex: response.addCookie(c1);
Cookie c[]=request.getCookie();
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 existing cookie and store it in the Cookie object.
• Set cookie age as zero using setMaxAge() method to delete an existing cookie
• Add this cookie back into the response header.
Ex:
Cookie ck=new Cookie("user",“cherry");
ck.setMaxAge(0);
response.addCookie(ck);
Set the Cookie Expiration Date
We can set the max age which defines how many seconds a given cookie should be valid
for:
Ex: cookie.setMaxAge(60*60);
We set a max age to one hour. After this time, the cookie cannot be used by a client
(browser)
• Methods of Cookie
•addCookie(Cookie ck): It is method of the HttpServletResponse interface which is used to
add cookie in response object.
•getMaxAge(): Gets the maximum age in seconds of this Cookie.
•getName(): Returns the name of the cookie.
•setName(): changes the name of the cookie.
•getPath(): Returns the path on the server to which the browser returns this cookie.
•getValue(): Gets the current value of this Cookie.
•setValue(String newValue): Assigns a new value to this Cookie.
•getVersion(): Returns the version of the protocol this cookie complies with.
•setMaxAge(int expiry): Sets the maximum age of the cookie in seconds.
•setVersion(int v): Sets the version of the cookie protocol that this Cookie complies with.
Example how to create by using Servlet
In this example, we are storing the name of the user in the cookie object and accessing it
in another servlet.
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.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close(); }
catch(Exception e){System.out.println(e);}
} }
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}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>
what is Session:

• It is the time period during which,the server is able to recognize the client uniquely in a
series of client-server interactions.
• HttpSession is another kind of session management technique, In this technique create
a session object at the server side for each client.
• Session is available until the session time out, until the client logout. The default
session time is 30 minutes and can configure explicit session time in the web.xml file.
What is HttpSession

It is an interface defined in javax.servlet.http package


HttpSession interface
The container creates a session id for each user.The container uses this id to identify the
particular user.An object of HttpSession can be used to perform two tasks:
1.bind objects
2.view and manipulate information about a session, such as the session identifier, creation
time, and last accessed time.
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

Disadvantages of Http session


•Performance overhead due to session object being stored on server
•Overhead due to serialization and de-serialization of data
How to get or create the HttpSession object?
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1.HttpSession getSession(): Returns the current session associated with this request, or if
the request does not have a session, creates one.
2.HttpSession getSession(boolean create): Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.
Ex:

HttpSession=request.getSession();

HttpSession=request.getSession (true);
Commonly used methods of the HttpSession interface
1.getId(): Returns a string containing the unique identifier value.
2.invalidate():Invalidates this session object or we can delete the session object
3.setAttribute():To set a attribute name and attribute value pair in the session object we
use
4.getAttribute():We can get attribute value associated with attribute name by using the
following method
Ex: session.setAttribute(“uid”,”cherry”);
Ex: session.getAttribute(“uid”));

5.getCreationTime(): Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
6.getLastAccessedTime():Returns the last time the client sent a request associated with
this session, as the number of milliseconds since midnight January 1, 1970 GMT.
Example of HttpSession by using Servlet
In this example, we are setting the attribute in the session scope in one servlet and getting
that value from the session scope in another servlet.
Index.html
<html>
<body>
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
CreateSession.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CreateSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}
}
GetSession.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>CreateSession</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>GetSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Output:
3) Hidden Form Field
• In the case of the Hidden Form Field a hidden (invisible) text field is used for
maintaining the state of user.
• In such case, we store the information in the hidden field and get it from another servlet.
• This approach is better if we have to submit forms in all the pages and we don’t want
to depend on the browser.
Let’s see the code to store value in a hidden field.
Ex:
<input type="hidden" name="uname" value=“web technologies">
Here, uname is the hidden field name and web technologies is the hidden field value.
Advantage of Hidden Form Field
It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
Extra form submission is required on each pages.
Only textual information can be used.
4.)URL Rewriting
• In URL rewriting, we append a token or identifier to the URL of the next Servlet or the
next resource. We can send parameter name/value pairs using the following format:
• url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, and 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 the getParameter() method to obtain a
parameter value.
Advantages of URL Rewriting
1.It will always work whether cookie is disabled or not (browser independent).
2.Extra form submission is not required on each page.
The disadvantage of URL Rewriting
1.It will work only with links.
2.It can send Only textual information.
JDBC Introduction
What is JDBC
• JDBC is a Service Technology from Sun microsystems that enables any kind of java
program can communicate with any kind of Data base in a standard manner.
• JDBC is an API
• JDBC is a Specification

• JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. This API consists of classes and interfaces
written in Java
• JDBC API is nothing but some special library methods that enable java programs to
perform database operations with the database.
• you can use JDBC to interact with a database from within a Java program. JDBC acts
as a bridge from your java program to the database
• JDBC API uses JDBC drivers to connect with the database.
JDBC Architecture
1.JDBC API
1. The API provides standard methods and interfaces to communicate with the
database.
2. The process is simplified by providing two packages java.sql. * and javax.sql.*.
3. The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
2.JDBC Driver Manager
1. The Driver Manager manages the list of database drivers.
2. It loads the database-specific Driver in the Java application to establish connectivity
with the database.
3. Java application request the Driver Manager for data base connectivity.It initiates the
connection process on the driver.Driver create the connection and gives to the Driver
manager which in turn gives to the java application.
4. Driver Manager is the Connection Provider to the Java Application.
3.JDBC Driver
• JDBC Driver is a translation software that enables java application to interact with
the database. It is written in java according to JDBC Specification.
• A JDBC driver uses the JDBC™ (Java Database Connectivity) API developed by Sun
Microsystems, now part of Oracle, that provides a standard way to access data using
the Java™ programming language.
• Driver Implements the JDBC API

Driver performs the following duties


1.Establish the data base connection for the client.
2.Receiving the JDBC Method calls.
3.Translating the method calls in to DBMS understandable calls.
4.Receiving the Results from the Database.
5.Translating the Results in to Java format and passing them to the client
• There are four types of JDBC drivers:
•JDBC-ODBC Bridge Driver,
•Native Driver,
•Network Protocol Driver, and
•Thin Driver
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
In Java 8, the JDBC-ODBC Bridge has been removed. Performance degraded because
JDBC method call is converted into the ODBC function calls.
Advantages:
•easy to use.
•can be easily connected to any database.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API.
It is not written entirely in java.
Advantage:
•performance upgraded than
• JDBC-ODBC bridge driver.
Disadvantage:
•The Native driver needs to be installed
•on the each client machine.
3.Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
•No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
•Network support is required on client machine.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Advantage:
•Better performance than all other drivers.
•No software is required at client side or server side.
Disadvantage:
•Drivers depend on the Database.
Explain the Database Connectivity Using JDBC
There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
1) Register the driver class/Loading the Driver
The forName() method of java. lang.Class class is used to register the driver class.
This method is used to dynamically load the driver class.
Example to register the Oracle Driver class
Here, the Java program is loading the mysql driver to establish a database connection
with Mysql Database.
Ex:
Class.forName("com.mysql.jdbc.Driver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish a connection
with the database.
Ex:
Connection con=DriverManager.getConnection(
“jdbc:mysql://localhost:3306/kiran","root","root");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the
database.
This method returns the object of ResultSet that can be used to get all the records of a
table.
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
5) Close the connection object
By closing the connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Example to close connection
Example of Login Form in Servlet using JDBC or Connecting the database using JDBC
•LOGIN.html
•LOGIN.java
•web.xml
•Step1 : create table login and with fields username and password and store some data.
•create table login(username varchar(20),password varchar());
Insert Data in login table
Ex:
•Sql> insert into login values(raj,raj123);
•Step 2: Design the login form with html
login.html
<html>
<head>
<title>Welcome To Login</title>
</head>
<body>
<center>
<form method="post" action="Log">
Name:<input type="text" name="name" /><br/><br/
Password:<input type="text" name="pass" /><br/><br/>
<input type="submit" value="Login" /><br/>
</form>
</center>
</body>
</html
Step3: Create the Servlet with the name Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("name");
String password = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/kiran","root","root");
PreparedStatement ps = con.prepareStatement
("insert into login values(?,?)");
ps.setString(1, username);
ps.setString(2, password);
int i = ps.executeUpdate();
if(i > 0) {
out.println("You are successfully registered at Amazon");
}
}
catch(Exception se) {
se.printStackTrace();
}
}
}
Step4 :create the deployment descriptor file ( web.xml)
<web-app>
<servlet>
<servlet-name>Log</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Log</servlet-name>
<url-pattern>/Log</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Step5: compile the servlet: javac
C:\Program Files\Apache Software Foundation\Tomcat
7.0\webapps\Login\WEB-INF\classes >javac Login.java

Step6:Start the Server and deploy the project


To start Apache Tomcat server, double clidouble-clickmcat7.exe file under
apache-tomcat/bin directory.
7) How to access the servlet
Open any browser then type the URL:

http://localhost:8085/webapp/Login/login.html

You will get the output

You might also like