Ip-Unit Iii Notes
Ip-Unit Iii Notes
Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions-
Session Handling- Understanding Cookies- Installing and Configuring Apache Tomcat Web
Server- DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example. JSP:
Understanding Java Server Pages- Creating HTML forms by embedding JSP code.
Servlet
Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
Servlet technology is robust and scalable because of java language.
There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
What is Servlet
Advantages of Servlet
Better performance: because it creates a thread for each request, not process.
Portability: because it uses Java language.
Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection , etc.
Secure: because it uses java language.
Read the explicit data sent by the clients (browsers). This includes an HTML form on
a Web page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or computing
the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document
can be sent in a variety of formats, including text (HTML or XML), binary (GIF
images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML),
setting cookies and caching parameters, and other such tasks.
The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method.
Notice that servlet is initialized only once. The syntax of the service method of the
Servlet interface is given below:
The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:
Servlet Example1
throws IOException
response.setContentType("text/html");
out.close();
Servlet Example2
throws IOException
response.setContentType("text/html");
out.close();
There are given 6 steps to create a servlet example. These steps are required for all the
servers.
Here, we are going to use apache tomcat server in this example. The steps are as
follows:
o Create a directory structure
o Create a Servlet
o Compile the Servlet
o Create a deployment descriptor
o Start the server and deploy the project
o Access the servlet
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.
The Sun Microsystem defines a unique standard to be followed by all the server
vendors. Let's see the directory structure that must be followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The web.xml
file must be under the WEB-INF folder.
2)Create a Servlet
DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different
jar files:
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.
There are many elements in the web.xml file. Here is given some necessary elements
to run the simple servlet program.
web.xml file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
To start Apache Tomcat server, double click on the startup.bat file under apache-
tomcat/bin directory.
You need to perform 2 tasks:
o set JAVA_HOME or JRE_HOME in environment variable (It is required to
start server).
o Change the port number of tomcat (optional). It is required if another server is
running on same port (8080).
Copy the project and paste it in the webapps folder under apache tomcat.
The web container is responsible to handle the request. Let's see how it handles the
request.
o maps the request with the servlet in the web.xml file.
o creates request and response objects for this request
o calls the service method on the thread
o The public service method internally calls the protected service method
o The protected service method calls the doGet method depending on the type of
request.
o The doGet method generates the response and it is passed to the client.
o After sending the response, the web container deletes the request and response
objects. The thread is contained in the thread pool or deleted depends on the
server implementation.
index.html
<!DOCTYPE html>
<html>
<head>
<title>doGet Example</title>
</head>
<body>
<form name="myform" action=“MyServlet" method=“get">
Enter Name:<input type="text" name="uname"><br><br>
Enter Age:<input type=“text" name=“uage"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
MyServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String age=request.getParameter(“uage");
out.println("<h3>Welcome to doGet Method</h3> ");
out.println("<br>Name:"+name);
out.println("<br>Age:"+age);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
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.
Session Tracking Techniques
There are four techniques used in Session tracking:
o Cookies
o Hidden Form Field
o URL Rewriting
o HttpSession
1. Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
Types of Cookie
There are 2 types of cookies in servlets.
o Non-persistent cookie
o Persistent cookie
Non-persistent cookie
o It is valid for single session only. It is removed each time when user closes the
browser.
Persistent cookie
o It is valid for multiple session . It is not removed each time when user closes
the browser. It is removed only if user logout or signout.
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides
a lot of useful methods for cookies.
How to create Cookie?
Let's see the simple code to create cookie.
Example
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
//creating submit button
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>
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the
state of an 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 form in all the pages and we don't
want to depend on the browser.
Let's see the code to store value in hidden field.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
Example
index.html
<form action="servlet1">
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 doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//creating form that have invisible textfield
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
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 doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
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.
Advantage of URL Rewriting
It will always work whether cookie is disabled or not (browser independent).
Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
It will work only with links.
It can send Only textual information.
Example
index.html
<form action="servlet1">
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 doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
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 doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("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>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>
HttpSession interface
In such case, 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:
bind objects
view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the object of
HttpSession:
index.html
<form action="servlet1">
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 doGet(HttpServletRequest request, HttpServletResponse response){
try{
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();
}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 doGet(HttpServletRequest request, HttpServletResponse response)
try{
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();
}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>
DATABASE CONNECTIVITY
JDBC
• Java Database Connectivity (JDBC) is an application programming interface (API)
for the programming language Java, which defines how a client may access a database
• It is Java based data access technology and used for Java database connectivity
• JDBC allows multiple implementations to exist and be used by the same application
• The JVM uses a JDBC driver to translate generalized JDBC calls into vendor specific
database calls
JDBC Architecture
• JDBC API
– JDBC API provides universal data access from the Java programming
language
– Using the JDBC API, you can access virtually any data source, from relational
databases to spreadsheets and flat files
– The JDBC API is comprised of two packages:
• java.sql
• javax.sql
• JDBC Driver Manager
– The DriverManager class acts as an interface between user and drivers
– It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver
– The DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver()
• JDBC Driver
– A JDBC driver is a software component enabling a Java application to
interact with a database
– JDBC drivers are analogous to ODBC drivers, ADO.NET data providers,
and OLE DB providers
– To connect with individual databases, JDBC (the Java Database
Connectivity API) requires drivers for each database
– The JDBC driver gives out the connection to the database and implements
the protocol for transferring the query and result between client and
database.
Drivers Types
• Type 1 - JDBC-ODBC Bridge
• Type 2 - Native API Driver
• Type 3 – Network-Protocol Driver
• Type 4 – Database-Protocol Driver
• Type 1 that calls native code of the locally available ODBC driver.
• Type 2 that calls database vendor native library on a client side. This code then talks
to database over the network.
• Type 3, the pure-java driver that talks with the server-side middleware that then talks
to the database.
• Type 4, the pure-java driver that uses database native protocol.
•
Type 1 - JDBC-ODBC Bridge
•
Uses a bridging technology to access a database. JDBC-ODBC bridge is an
example. It provides a gateway to the ODBC.
• Type 2 - Native API Driver
• Native API drivers.
• Driver contains Java code that calls native C/C++ methods provided by the
database vendors.
• Type 3 – Network-Protocol Driver
• Generic network API that is then translated into database-specific access at the
server level.
• The JDBC driver on the client uses sockets to call a middleware application on
the server that translates the client requests into an API specific to the desired
driver. Extremely flexible.
• Type 4 – Database-Protocol Driver
• Using network protocols built into the database engine talk directly to the
database using Java sockets. Almost always comes only from database
vendors.
Type-1 JDBC-ODBC Bridge
• Converts JDBC method calls into ODBC function calls
• Platform-dependent
• ODBC must be installed on the computer having the driver
• Sun (now Oracle) provided a JDBC-ODBC Bridge
river: sun.jdbc.odbc.JdbcOdbcDriver.
• Advantages
– Almost any database for which an ODBC driver is installed can be accessed,
and data can be retrieved.
• Disadvantages
– Performance overhead
– The ODBC driver needs to be installed on the client machine.
– Not suitable for applets
– Specific ODBC drivers are not always available on all platforms
– No support from JDK 1.8 (Java 8) onwards.
Type 2 - Native API Driver
• It is a database driver implementation that uses the client-side libraries of the database
• converts JDBC method calls into native calls of the database API
• Advantages
– As there is no implementation of JDBC-ODBC bridge, it may be considerably
faster than a Type 1 driver.
• Disadvantages
– The vendor client library needs to be installed on the client machine.
– Not all databases have a client-side library.
– This driver is platform dependent.
– No Applets support
Type 3 – Network-Protocol Driver
• Class.forName()
– The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.
• DriverManager class
– The DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
– public static Connection getConnection(String url,String
userName,String password):establish the connection with the specified url,
username and password.
• Connection interface
– A Connection is the session between java application and database.
– public Statement createStatement():creates a statement object that can be
used to execute SQL queries.
– public void close(): closes the connection and Releases a JDBC resources
immediately.
• Statement interface
– provides methods to execute queries with the database.
– public ResultSet executeQuery(String sql): is used to execute SELECT
query. It returns the object of ResultSet.
– public int executeUpdate(String sql): is used to execute specified query, it
may be create, drop, insert, update, delete etc.
• ResultSet interface
– maintains a cursor pointing to a row of a table. Initially, cursor points to before
the first row.
– public boolean next():is used to move the cursor to the one row next from
the current position.
– public int getInt(int columnIndex):return the data of specified column index
of the current row as int.
– public int getInt(String columnName):return the data of specified column
name of the current row as int.
– public String getString(int columnIndex):return the data of specified
column index of the current row as String.
– public String getString(String columnName):return the data of specified
column name of the current row as String.
• PreparedStatement interface
– a subinterface of Statement
– It is used to execute parameterized query.
– Eg.: String sql="insert into emp values(?,?,?)";
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to Servlet because it provides more functionality
than servlet such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags.
The JSP pages are easier to maintain than Servlet because we can separate designing
and development.
It provides some additional features such as Expression Language, Custom Tags, etc.
Advantages
1) Extension to Servlet
2) Easy to maintain
3) Fast Development: No need to recompile and redeploy
4) Less code than Servlet
The scripting elements provides the ability to insert java code inside the jsp. There are
three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
Example
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Expression tag
The code placed within JSP expression tag is written to the output stream of the
response.
So you need not write out.print() to write data. It is mainly used to print the values of
variable or method.
Example
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Declaration Tag
Syntax
<%! field or method declaration %>
Example
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
The jsp scriptlet tag can only declare The jsp declaration tag can declare variables as
variables not methods. well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is placed
inside the _jspService() method. outside the _jspService() method.
JSP directives
The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
There are three types of directives:
o page directive
o include directive
o taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
Include Directive
The include directive is used to include the contents of any resource it may be jsp file,
html file or text file.
The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include
static resource).
Example
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Taglib directive
The JSP taglib directive is used to define a tag library that defines many tags.
We use the TLD (Tag Library Descriptor) file to define the tags.
In the custom tag section we will use this tag so it will be better to learn it in custom
tag.
Example
<html>
<body>
<mytag:currentDate/>
</body>
</html>
Action Tags
There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The
Jsp action tags are given below.
<html>
<body>
</jsp:forward>
</body>
</html>
page2.jsp
<html>
<body>
</body>
</html>
jsp:include
<html>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>