WT Unit 3
WT Unit 3
WT Unit 3
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.
• CGI stands for Common Gateway Interface and provides an interface between the HTTP
Server and programs generating web content.
• known as or simply as
• 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.
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
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
Servlet Declares life cycle methods that all servlets must implement.
Classes Description
ServletOutputStream Provides an output stream for sending binary data to the client.
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.
7. getInitParameter(String name):It returns the parameter value for the given parameter
name.
• 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>
</html>
AddServlet.java
import java.io.*;
import javax.servlet.http.HttpServlet.*;
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();
<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.
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">
</form>
</html>
AddServlet.java
import javax.servlet.*;
import java.io.*;
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:
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>
<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.
• 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
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
http://localhost:8085/webapp/Login/login.html