Unit-3 session mgmt
Unit-3 session mgmt
DATABASE CONNECTIVITY IN
SERVLET
Structure
3.0 Introduction
3.1 Objectives
3.2 Session Management
3.2.1 HttpSession
3.2.2 Cookies
3.2.3 URL Writing
3.2.4 Hidden Fields
3.3 Servlet Collaboration
3.3.1 Using RequestDispatcher Interface
3.3.1.1 forward() Method
3.3.1.2 include() Method
3.3.2 Using HttpServletResponse Interface
3.3.2.1 sendRedirect() Method
3.3.3 Using ServletContext Interface
3.3.3.1 setAttribute() Method
3.3.3.2 getAttribute() Method
3.4 Database Connectivity
3.4.1 Insert data into Database
3.4.2 Retrieve Data from Database
3.5 Summary
3.6 Solutions/Answers to Check Your Progress
3.7 References/Further Reading
3.0 INTRODUCTION
In the previous unit, you have already gone through the basics of Servlets in detail
which are a server side programming language. As you know that the servlets are used
for dynamic web application. Several users interact with such web applications
simultaneously. Do you know how to manage this dynamic application among the
users? A strategy called session management is applied in these applications. In this
unit, you will learn more about session management. In Java Servlet, session is
managed through different techniques such as HttpSession object, Cookies, URL
rewriting and Hidden Form field. For example, when you check your result on the
IGNOU website and put your roll number in the input field, it shows that some roll
numbers might appear for your selection. It is all possible by the cookies. You will
find explanations and examples of these techniques used in session management.
In addition, this unit introduced you to Servlet Collaboration which is all about
sharing information among the servlets. The Servlet-API provides the
RequestDispatcher, HttpServletResponse and ServletContext interface to achieve
Servlet Collaboration. RequestDispatcher interface is useful for forwarding the
request to another web resource and including the resource in the current servlet.
HttpServletResponse interface makes available a method sendRedirect to
communicate with others. A servlet can also share information among multiple
1
Web Application
Development using J2EE servlets by using setAttribute and getAttibute method of ServletContext. This unit
explains to you how the servlets communicate with each other using the methods
defined in these three interfaces. Apart from these, this unit also enlightens you about
database access using Java Database Connectivity (JDBC) technology.
In the previous unit, you have already gone through the procedure of compiling as
well as after compiling servlet made entries in deployment descriptor (web.xml) file
and invoked them from a web browser. The previous Unit also defined the creating
and running procedure of servlet in NetBeans. This Unit is also devoted to the
servlets. So, there is no need to define the same procedures again.
3.1 OBJECTIVES
In the previous unit, you studied the Java Servlets used to create dynamic content-
based web pages or web applications. Dynamic web pages are different from static
web pages in which web server creates a web page when a web client or user requests
it. For example, when you check your online results on IGNOU website, different
pages are generated for different students by the IGNOU web server depending on
your enrolment number.
We all know that HTTP is a stateless protocol which is explained in the previous Unit.
It means that the HTTP protocol does not remember information when client or user
communicates with the server. Whenever you send a request to the server through
HTTP, the HTTP treats each request as a new request. But sometimes in web
applications, clients are doing some important work such as online shopping, online
banking etc. In that situation, it is necessary to know about the client and remember
the client's request accordingly. For example, an online banking application system
enables many clients to do their different activities like checking account balance(s),
obtaining statements and making financial transactions simultaneously. For
maintaining each client’s session, you can use session management.
Before going into session management details, you should know about the two
important terms, i.e. session and state, which are necessary for implementing business
transactions across multiple clients. These are as under:
Session: The server should recognize a series of requests from the same user which
form a single working ‘session’. For example, in net banking application, each client
can be differentiated from another client by associating a unique identifier in request
and response within a specific working session.
2
Session Management and
State: The server should be able to remember information related to the previous Database Connectivity in
request and other business transaction that are made for that request. For example, in Servlet
net banking application, state comprises client information such as account number
and amount transaction made within the particular session.
Do remember one thing-- session management does not change the nature of HTTP
protocol i.e., stateless feature provides a way to remember the client information.
Session management is also known as session tracking, which permits Servlet/JSP to
maintain information about a series of request from the same client. It is a mechanism
to store session information for each client. For example, When a user visits any web
application, unique identification information about the user is stored in an object
available during the particular session until the user quits the web application.
There are four ways to manage sessions: HttpSession object, Cookies, URL rewriting,
and hidden fields.
3.2.1 HttpSession Object
Any dynamic website or web application uses the concept of sessions and Session
object to store data for a particular user. For example, when you visit any web
application for the first time, you have entered login name and password. This
information might be stored in session variable and maintained by the servlet
container during your visit to web application so that it can be accessed when needed.
When your session is started, the requesting browser is allotted a unique id for each of
the clients for identifies the client. This Session object is denoted by
javax.http.HttpSession interface.
You have learned about the HttpSession interface under the Servlet API in the
previous Unit. Servlet API provides session management through HttpSession
interface. This HttpSession interface provides a mechanism to identify a user to
examine who is visiting a web application and to store the user information. Servlet
Container creates a session id for each user. You can maintain state between the
transactions by using methods of HttpSession interface.
Example -1
The following example will explain to you about session management using the
methods defined in the HttpSession interface.
Following servletSession.java is servlet program that uses session tracking to keep
track of how many times a particular user has accessed a page and to display some
details of the current session such as Session identifier, Creation Time and Last
Access Time. The source code of this program is listed below:
servletSession.java
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class servletSession extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
Integer ct = (Integer) session.getAttribute("ct");
if (ct == null)
{ ct = new Integer(1); }
3
Web Application
Development using J2EE else { ct = new Integer(ct.intValue()+1); }
session.setAttribute("count", ct);
out.println("Session Details: ");
out.println("<br/>");
out.println("You have visited this page : " + ct + ((ct.intValue() ==1)? " time" : " times")
);
out.println("<br/>");
out.println("Session ID : " + session.getId());
out.println("<br/>");
out.println("New Session : " + session.isNew() );
out.println("<br/>");
out.println("creation Time : " + new Date(session.getCreationTime()));
out.println("<br/>");
out.println("Last Access Time : " + new Date(session.getLastAccessedTime()));
}
}
You already have learnt about the running procedure of servlet and methods included
in the above servlet program in Unit 2 Block 1 of this course. Compile the above
servlet, put the class file in the classes folder, and create appropriate entry in the
web.xml file under the WEB-INF folder in your ‘webapps’ folder. Now, you can start
your web server and run the program from your browser.
When you access this program for the first time, the visiting counter will be one and
the new Session will ‘true’. When visiting counter increases in numbers the new
session will be ‘false’. This program will also display some details of the current
session such as Session identifier, Creation Time and Last Access Time.
When you will run your Project in NetBeans it is displayed as output like the figure-
2:
4
Session Management and
Database Connectivity in
Servlet
When you will click on ‘Session Servlet Program’ link, then servlet will run and give
output as Figure-3:
3.2.2 Cookies
In the last section, you have studied session management through HttpSession object
in Servlet. Here you will learn about Cookies. This is another session management
technique. Cookies are a small part of information like a name, a single value and
optional attributes such as comment, path and domain qualifiers, a maximum age, and
a version number. A servlet sends this cookie information to a web browser. It is
saved by the browser and later sent back to the server. The browser probably
supports 20 cookies for each Web server, 300 cookies total and may limit cookie size
to 4 KB each. You can uniquely identify a client through cookie's value, so cookies
are generally used for session management. If the client disables the cookies then it
won’t work and you cannot maintain a session with cookies.
There are two types of cookies such as Non-persistent cookie and Persistent cookie in
servlets. The Non-persistent cookie is effective for a single session only and
removed each time when the user closes the browser. On the contrary, Persistent
cookie is effective for multiple sessions, and it is removed only when user logouts.
A cookie is indicated by the Cookie class in the javax.servlet.http package. You can
create a cookie by calling Cookie class like the following:
Cookie c = new Cookie(“userid”, “socis”);
You can send the cookie to the client browser by using addCookie() method of the
HttpServletResponse interface like the following:
response.addCookie(c);
5
Web Application
Development using J2EE You can retrieve cookies from request using getCookie() of the HttpServletRequest
interface like the following:
request.getCookie(c);
Example -2
The following example demonstrates to you how to create cookies and how these
cookies are transferred to another servlet. This example contains one HTML form
(cookieForm.html) and two servlet programs (CreateCookieServlet.java and
GetCookieServlet.java).
The source codes of the programs are given below:
cookieForm.html
CreateCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
GetCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet
{
6
Session Management and
public void doPost(HttpServletRequest request, HttpServletResponse response) Database Connectivity in
{ Servlet
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie c[] = request.getCookies();
out.println("Welcome in SOCIS "+c[0].getValue());
}
catch(Exception e){System.out.println(e);}
}
}
Now, you can compile both the servlets program and place class files in the classes
folder of the your web application. Also, make an entry in the deployment descriptor
file and first run the HTML form program from your browser. When you submit your
data by clicking submit button of the HTML program (see figure-4), the control is
transferred to CreateCookieServlet program (see figure-5).
7
Web Application
Development using J2EE 3.2.3 URL Writing
In the previous section, you have learnt two session management techniques i.e.
HttpSession Object and Cookies. The third technique that you can use to maintain
user sessions is by using URL writing. In this approach, the token (parameter) is
embedded in each URL. When client submits request using such URLs, the token is
retransmitted to the server. In each dynamically generated page, server embeds an
extra query parameter or extra path information. If a browser does not support cookies
then in that case URL rewriting technique is the best alternative for session
management.
Using URL Writing technique, you can send parameter name/value pairs like the
following:
http://myserver.com?name=xyz&age=20
When you click on URL, the parameter name/value pair will transfer to the servlet.
The servlet will fetch this parameter by using getParameter() method of
HttpServletRequest interface from the requested URL and use it for session
management.
Example -3
The following example will show you how to work URL Writing technique with
session management. This example comprises the 3 programs such as html form
(URLWritingForm.html) and two Servlet program (CreateURLServlet.java and
FetchURLServlet.java). The source codes of programs are listed below:
URLWritingForm.html
<html>
<head><title>URL Writing Session FORM</title></head>
<body>
<form action="../servlet/CreateURLServlet" method="post">
<fieldset>
<legend>Student Details</legend>
Student Name :<input type="text" name="uname"> <br>
Password: <input type="password" name="pwd"> <br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body></html>
CreateURLServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CreateURLServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("uname");
String password = request.getParameter("pwd");
8
Session Management and
if(password.equals("socis")) Database Connectivity in
{ Servlet
response.sendRedirect("FetchURLServlet?username="+ name);
}
else
{out.println("Password is incorrect");}
}
}
FetchURLServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FetchURLServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
out.println("Welcome in SOCIS, "+name);
}
}
Now, you can compile both the servlet programs and place class file in ‘classes’
folder. Also make entry in web.xml file and start web server. Finally, you can run
URLWritingForm.html file from your browser. Here, you can submit your data such
as student name, password and click on ‘Submit’ button (see Figure-7)
After fetching the parameter value, the FetchURLServlet program will display output
You can get this hidden field in Java Servlet using the getParameter() method of
HttpServletRequest interface.
String param1 = request.getParameter("userid");
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------------------------
2. Write a servlet program by using HttpSession Object of session management.
Servlet program will display creation time when user will visit web page for
the first time else it displays last access time. Also display session ID in both
the conditions.
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------------------------
3. What is the difference between a session and cookie?
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------------------------
10
Session Management and
Database Connectivity in
3.3 SERVLET COLLABORATION Servlet
In the previous section, you have gone through the session tracking techniques. Using
these techniques, you can track a series of user requests. This section describes to you
how servlets share information between two or more servlets.
Servlets running together under the same server, need to communicate with each
other for exchanging data information. When two or more servlets can communicate
or share common information, you can call it Servlet Communication or Servlet
Collaboration.
Servlet collaboration means sharing information among the servlets. This tactic
requires each servlet to know the other servlet with which it collaborates. Sometimes,
a situation arises in program coding when you may require passing the request from
one servlet to another. Also, you may want to include the content from HTML, JSP or
Servlet into your servlet. Java provides Servlet-API to accomplish Servlet
Collaboration and Servlet-API covers two interfaces namely:
javax.servlet.RequestDispatcher and javax.servlet.http.HttpServletResponse. Both
interfaces have various methods which are used for sharing information between
servlets.
For using a servlet forward() or include() method, you first need to obtain a
RequestDispatcher object. You can obtain a RequestDispatcher object like the
following:
11
Web Application
Development using J2EE RequestDispatcher rd = request.getRequestDispatcher(String resource);
Example-4
The following example explains how to use both the forward() and include() method
of RequestDispatcher interface to achieve Servlet Collaboration. This example
comprises one HTML program (loginForm.html) and two servlets programs
(RequestDispatcherServlet.java and WelcomeStudentServlet.java). The LoginForm
contains two input fields i.e., name and password. RequestDispatcherServlet program
received data from LoginForm and compares statically with given data in the servlet
program. If a match is done, control is transferred to the WelcomeStudentServlet
program, else control gets back to LoginForm again to re-enter the data.
The source codes of all three programs are listed below:
LoginForm.html
<html>
<head></head>
<body>
<form action="../servlet/RequestDispatcherServlet" method="post">
<fieldset>
<legend>Student Details</legend>
Student Name: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
RequestDispatcherServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestDispatcherServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name=req.getParameter("user");
String pass=req.getParameter("pwd");
if(name.equals("Ram") && pass.equals("socis"))
{
RequestDispatcher rd=req.getRequestDispatcher("WelcomeStudentServlet");
rd.forward(req, res);
}
else
{
out.print("User name or password is incorrect!");
RequestDispatcher rd=req.getRequestDispatcher("../servlets/LoginForm.html");
12
Session Management and
rd.include(req, res); Database Connectivity in
} Servlet
}
}
WelcomeStudentServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeStudentServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("user");
out.print("Welcome in IGNOU, "+name+"!");
}
}
You can compile both the servlet programs and make a suitable entry in web.xml file.
Now you can start the web server and run HTML form through the browser.
When you run your LoginForm.html, it will display like the following Figure-10 with
two input fields. When you enter student name and Password and click on submit
button then action control goes to the RequestDispatcherServlet program.
When you input the Student Name as Ram and Password as socis then it will welcome
you (see figure-11); otherwise, it will ask to re-enter values (see figure-12)
13
Figure 12 Request Dispatcher example, Login Form Screen
Web Application
Development using J2EE
3.3.2 Using HttpServletResponse Interface
The HttpServletResponse Interface captures the functionality of a response object that
is returned to the client from an HTTP servlet. The interface HttpServletResponse
offers many protocol-specific methods which are not available in ServletResponse
interface. The interface HttpServletResponse extends the
javax.servlet.ServletResponse interface. You have already explored two of the
methods in HttpServletResponse at the time of servlet writing in this unit as well as
Unit 2. These two methods setContentType() and getWriter() are used when sending
output to the browser. The setContentType(java.lang.String type) method is used to
set the type of the response data e.g. text, HTML etc. The getWriter() method returns
the PrintWriter object for sending text data to the client.
res.setContentType("text/html");
PrintWriter out = res.getWriter();
response.sendRedirect("http://www.ignou.ac.in");
In the previous section, you have studied forward() method. Function of both the
methods forward() method of RequestDispatcher interface and sendRedirect() of
RequestDispatcher interface are almost similar but they differ also.
In servlet programming, servlet context is the environment where the servlet runs. The
ServletContext’s object is created by the web container at the time of deploying the
project. Using this you can use to access all the resources available within the
application and to store attributes which other servlets with the same context can use.
You can use one context per "web application" per Java Virtual Machine. The
ServletContext object is used to get configuration information from deployment
descriptor file (web.xml), which will be available to any servlet or JSPs that are
component of the ‘webapps’.
The ServletContext Interface defines various methods which are used by servlets to
communicate with its servlet container. For example, dispatch requests or writes to a
log file to get the MIME type of a file. The object of ServletContext can be added and
retrieved from the context using the setAttribute and getAttribute methods.
When you have defined ServletContext object, you can set attributes of
ServletContext object by using the setAttribute() method. From now, ServletContext
object is available to all the servlets of the web application. By using the
getAttribute() method, other servlets can get the attribute from the ServletContext
object.
String name: By providing the value of this argument, you can specify the name of
attribute.
Object obj: By providing the value of this argument, you can specify the value of the
named attribute.
Example- 5
15
Web Application
Development using J2EE The following example explains to you how setAttribute() and getAttribute() method
works with the ServletContext.
The example uses two servlets: ServletDemo1 and ServletDemo2 and one HTML
Form (Login.html). This form comprises two input fields such as name and
percentage of student. A student must have a percentage of more than 80. When the
user submits the form, control will transfer to the ServletDemo1 servlet.
The ServletDemo1 servlet received two input values i.e. name and percentage by
using getParameter() method from html form. This servlet uses setAttribute() method
to bind name attribute and does this by first obtaining the ServletContext object.
Here, this servlet checks percentage if percentage is more than 80, then the control
will pass to the ServletDemo2 servlet, otherwise control will transfer to Login form to
fill data again.
In ServletDemo2 servlet, after getting the ServletContext object, you can use
getAttribute() method to get name attribute.
Login.html
<fieldset>
<legend>Student Details</legend>
ServletDemo1.java
import java.io.*;
import javax.servlet.*;
public class ServletDemo1 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
//Creating ServletContext object
ServletContext sc = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Using ServletContext object to set and read attributes");
out.println("<br/>");
String uname = request.getParameter("username");
int Per = Integer.parseInt(request.getParameter("percent"));
//Setting name attribute to be shared between multiple servlets
sc.setAttribute("Name", uname);
if( Per > 80)
{
16
Session Management and
RequestDispatcher rd = sc.getRequestDispatcher("/servlet/ServletDemo2"); Database Connectivity in
rd.forward(request,response); Servlet
}
else
{
out.print("Data is incorrect!");
out.println("<br/>");
out.print("Fill your data again");
RequestDispatcher rd = sc.getRequestDispatcher("/servlets/Login.html");
rd.include(request,response);
}
}
}
ServletDemo2.java
import java.io.*;
import javax.servlet.*;
public class ServletDemo2 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
ServletContext sc = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>" + "Congratulations! " + sc.getAttribute("Name") + "</b>");
}
}
Now, you can compile both servlets and create appropriate entry in web.xml file.
Finally, you can start server and run the Login form from your browser. The output of
the html program is displayed like the following figure13.
Here you can submit your data. The flow controls of servlets depends on your
percentage. If you submitted more than 80, you will get congratulations (see figure-
14), this procedure is defined in the ServletDemo2 servlet otherwise you will get back
to login again to re-enter data (see figure- 15)
17
Web Application
Development using J2EE
When the condition is false, you will get the following to re-enter data:
18
Session Management and
In the previous section, you have studied more about the advanced features of servlets Database Connectivity in
with examples, but all this work has been done statically without any database Servlet
connectivity. This section will provide you in-depth knowledge of data access,
specifically insertion and retrieval of data to/from a database.
Database access is one of the important features of Web application. Java has its own
technology for database connectivity called JDBC (Java Database Connectivity).
JDBC provides a standard library for accessing a wide range of relational databases
like MS-Access, Oracle and Microsoft SQL Server. Using JDBC API, you can access
a wide variety of different SQL databases. The core functionality of JDBC is found in
java.sql package.
Consider a table named as Student created in Microsoft SQL Server database with
Roll No, Name and Program name. This table is used in both the following sections.
This section defines example(s) for storing/retrieving data into/from a Microsoft SQL
Server using type-4 JDBC driver. You can run these programs on any web server such
as Tomcat. For running these programs, you need a JDBC driver in .jar form and
placing them in lib directory under the web server.
For inserting data into a database, you can use the following example.
Example - 6
The following example will demonstrate to you how to store data in a database using
servlet. For this, create a HTML Student Form and one Servlet for storing data into a
database.
The student form contains student’s details like student enrolment no., student name
and Programme name. You will have to create a student table with related fields of
student form. When you submit these details, access ‘DataStoreServlet’ to store data
into the database.
The DataStoreServlet program is written similar to the above servlet programs with
database query and ‘try’ and ‘catch’ clause of standard Java mechanism.
StudentForm.html
<html>
<body>
<form action="../servlet/DataStoreServlet" method="post">
<h3>Indira Gandhi Open University </h3>
<fieldset>
<legend><b>Student Details </b></legend>
</fieldset>
</form>
19
Web Application
Development using J2EE </body>
</html>
In the following servlet program, the first step is to get the data from
‘StudentForm.html’ program using request.getParameter() method. After connecting
to database, an insert query is executed using executeUpdate() method.
DataStoreServlet.java
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DataStoreServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String rollNo = req.getParameter("sid");
String StuName = req.getParameter("sname");
String prgName = req.getParameter("prg");
//create connection object
Connection con = null;
// create statement object
Statement stmt = null;
// connection string using Type-4 Microsoft SQL Server driver
// you can also change the next line with your own environment
String url=
"jdbc:microsoft:sqlserver://127.0.0.1:1433;user=sa;password=poonam;DatabaseN
ame=SOCIS";
try
{
// load JDBC type-4 SQL Server driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection(url);
if (con != null)
{
stmt = con.createStatement();
//insert query
String rsql ="insert into student
values("+rollNo+",'"+StuName+"','"+prgName+"'"+")";
//execute query
stmt.executeUpdate(rsql);
out.println("Your data is successfully stored in database");
}
if(con == null)
{ con.close(); // release connection }
}
// end of try clause catch(SQLException se)
{ out.print("SQL:"+se.getMessage());}
catch(Exception e)
{ out.print("Exception:"+e.getMessage());}
}
}
20
Session Management and
Database Connectivity in
As earlier, you can compile the above servlet and make related entry in deployment Servlet
descriptor file (web.xml) then start your web server and run your StudentForm.html
file from your browser. When you run your form, it will display output like the
following figure-16:
Figure 16: Student data Form for storing data into database
In the above screen, when you will enter values then the following screen (figure-17)
will show you a message for successful data storage.
We have just seen in the previous section about the storage of data into a database
using servlet program. This section explains to you how to retrieve some data from a
database. Figure 17: Data stored in persistent storage
Example-7
The following example gives you an illustration about how to retrieve data from the
database. After execution of the above DataStoreServlet program, you have stored
sufficient data into the database. Now, you will execute the following code for
retrieving the data from the database. In this program, one additional ResultSet object
is used for retrieving data from the select query. The data is retrieved from ResultSet
object by using getXXX() method such as getInt() and getString(). Note that if the
column name is an integer type, then you should use getInt() method instead
getString() method. The following RetDataServlet program is listed for retrieving data
from database.
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RetDataServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection con = null; //create connection object
Statement stmt = null; // create statement object
ResultSet rs = null; // create ResultSet object
21
Web Application
Development using J2EE // connection string using Type-4 Microsoft SQL Server driver
// you can also change the next line with your own environment
String url=
"jdbc:microsoft:sqlserver://127.0.0.1:1433;user=sa;password=poonam;DatabaseN
ame=SOCIS";
try
{
// load JDBC type-4 SQL Server driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection(url);
if (con != null)
{
stmt = con.createStatement(); // select SQL statement
String rsql ="select * from Student";
rs = stmt.executeQuery(rsql); //execute query
out.println("<table border=1><tr><td>Roll Number</td><td>Student
Name</td><td>Programme</td></tr>");
while( rs.next() )
{
out.println("<tr><td>" + rs.getInt("RollNo") + "</td>");
out.println("<td>" + rs.getString("Student_Name") + "</td>");
out.println("<td>" + rs.getString("Programme") + "</td></tr>");
}
out.println("</table>");
}
if(con == null) {con.close();}
}
catch(SQLException se){ out.println("SQL:"+se.getMessage());}
catch(Exception e){ out.println("Exception:"+e.getMessage());}
}
}
Now, you can compile the above servlet and make entry in deployment descriptor file
(web.xml), start your web server and run your servlet program from your browser.
After running the RetDataServlet program, the data will be displayed on your output
screen like following figure-18:
If you want to build your project using Oracle or other database as back end then you
can change only port no. and relevant JDBC driver name in above servlet source code.
3.5 SUMMARY
In this unit, you have learned how to use session management using four techniques:
HttpSession object, Cookie, URL Writing, and Hidden form field. You have been
shown a number of examples to demonstrate the use of session management in the
22
Session Management and
servlets. In addition, this Unit introduced you to Servlet collaboration which is all Database Connectivity in
about sharing information among the servlets. The Servlet-API provides the Servlet
RequestDispatcher interface to achieve Servlet Collaboration. This interface is useful
for forwarding the request to another web resource and including the resource in the
current servlet. Apart from these, this unit also discussed database access using Java
Database Connectivity (JDBC) technology.
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class sessionServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
if ( session.isNew())
{
out.println("New Session : " + session.isNew() );
out.println("<br/>");
out.println("Session ID : " + session.getId());
out.println("<br/>");
23
Web Application
Development using J2EE out.println("creation Time : " + new Date(session.getCreationTime()));
}
else
{
out.println("New Session : " + session.isNew() );
out.println("<br/>");
out.println("Session ID : " + session.getId());
out.println("<br/>");
out.println("Last Access Time : " + new
Date(session.getLastAccessedTime()));
}
}
}
3) Both the Session and Cookie are used to store information. The session is
stored in server-side machine, whereas Cookies are stored on the client-side
machine. Session should work regardless of the settings on the client browser.
Session data will be available to all pages on the site during the particular
session of visit. Session can store objects, and cookies can store only strings.
Cookie expires depending on the lifetime you set for it whereas a Session
ends when a user closes the browser or after leaving the site.
2) Both the methods bring the user to a new web resource. Both are similar but
there is a fundamental difference between the two. The difference between
two methods is as follows:
• The forward method can be used to redirect the request without the help
of the client browser and control transfer remains within-applications
resources only. The sendRedirect method can redirect the request to the
client browser and control transfer goes outside the current domain.
• In forward method, HttpServletRequest object and
HttpServletResponse object are passed to the new resource whereas in
sendRedirect method, previous HttpServletRequest object is lost. For
passing information between the original and new request, you can pass
the information as a query string appended to the destination URL.
3) The source code of servlet by using sendRedirect() method is given below:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
24
Session Management and
public class sendRedirectServlet extends HttpServlet Database Connectivity in
{ Servlet
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
res.sendRedirect("http://www.ignou.ac.in/");
}
}
25