30 SERVLET SESSION and SERVLET WITH JDBC

Dr M. Vijayalakshmi

 

Session Management API

 

Session Management API is built by utilizing the different concepts used in the different approaches we have already explained for session tracking. There were disadvantages that exists in the previous approaches and all the previous methods are not complete by themselves. Hence it is required to provide a solution that can utilize these concepts of session tracking to provide session management in all cases.

 

Java provides Session Management API and J2EE Servlet technology that we can use to maintain sessions.

    Session Management

 

When a Http client interacts with the web server, a session id is created and for subsequent requests by the client the same session id is used to recognize the client by the server. This session is maintained until the client disconnects from the server or closes his browser.This is shown diagrammatically for two clients interacting with the server with its own session id in Figure 32.1.

 

     Session Tracking in Java

 

Servlets include a built-in Session API. A server complying with the Java servlet API supports the session concept by associating an HttpSession object with each session maintained by the server. HttpSession object is created by the server when a servlet call the getSession() method on its HttpServletRequest parameter.The following syntax is used to create HttpSession object.

    HttpSession session = request.getSession();

 

Using the Session API

 

Steps to use the Java Session API:

 

1)  Get the Session object from the HTTPSession object.

2) Extract Data from the user’s Session Object

3) Extract information about the session object” e.g. when was the session created, session ID etc.

4) Add data to the user’s Session Object.

 

Session Tracking Basics

 

The basic steps we follow to work with session tracking is given below.

 

• Access the session object.

 

Use the method request.getSession to get HttpSession object.

HttpSession session = request.getSession();

 

• Look up information (user data) associated with a session.

 

Use the method getAttribute on the HttpSession object to get information associated with the session.

 

• Store information in a session.

 

Use the method setAttribute with a key and a value to add data to the user’s session object.

  • Discard session data.

       Use the method removeAttribute that discards a specific value associated with a specified “key” (This is the most common approach used).

 

We can call invalidate to discard an entire session and all user data will be lost including the data created by other Servlets or JSP pages.

 

HttpSession Object Methods

 

Some of the useful methods to work with HttpSession object is given in Table 32.1.

 

 

  Example: DateServlet

 

This Servlet program is to demonstrate about maintaining session which displays the last accessed date and the current date of the session whenever the Servlet is invoked.

 

The first step is to create a new session object using the getSession() method of HttpServletRequestobject to associate a session with the Servlet. Initially no date is associated with the session hence when the first time the Servlet is invoked, it displays the current date/time. This date object created is set with the session using the method setAttribute() of the HttpSession object. When the next time the Servlet is called, it retrieves the date from the session object using the method getAttribute() and displays the last accessed date and the current date.

 

import java.io.*;

importjava.util.*;

importjavax.servlet.*;

importjavax.servlet.http.*;

public class DateServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException

{

HttpSession hs= request.getSession(true);

response.setContentType(“text/html;charset=UTF-8”);

try (PrintWriter out = response.getWriter())

{

out.println(“<!DOCTYPE html>”);

out.println(“<html>”);

out.println(“<head>”);

out.println(“<title>Servlet AddCookieServlet</title>”);

out.println(“</head>”);

out.println(“<body><center>”);

out.print(“<B>”);

//Display date/time of last access.

Date date=(Date)hs.getAttribute(“date”);

if(date!=null) {

out.print(“Last access: “+ date        +”<br>”);

}

//Display current date/time.

date=new Date();

hs.setAttribute(“date”,date);

out.println(“Current date: “+date);

out.println(“</center></body>”);

out.println(“</html>”);

}

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException

{

processRequest(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)mthrowsServletException, IOException

{

processRequest(request, response);

}

public String getServletInfo() {

return “Short description”;

}

}

}

    Web.xml

 

We need to compile the above servlet, DateServlet and create appropriate entry in web.xml file.

 

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns=”http://xmlns.jcp.org/xml/ns/javaee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee Http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd” version=”3.1″>

<session-config>

<session-timeout>

</session-timeout>

</session-config>

<servlet>

<servlet-name>HttpSess</servlet-name>

<servlet-class>DateServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HttpSess</servlet-name>

<url-pattern>/DateServlet</url-pattern>

</servlet-mapping>

</web-app>

     DateServlet Output

 

Figure 32.2 shows the output of the DateServlet when the servlet is invoked initially.

 

 

After sending another request Output

 

The output of the DateServlet when the servlet is invoked subsequently shown in Figure 32.3.

 

 

    Session Tracking Example

 

The following Servlet demonstrates the use of session, by counting the number of accesses within this session from a particular client. The example illustrates the use of methods like getID() to retrieve the session ID, getCreationTime() and getLastAccessedTime() to get the session creation and last accessed times.The   first    step    is    to    create    a   new    session    object    using    the getSession() method of HttpServletRequest.

“Welcome to my website”

  Then we get the session ID using the method getID(), session creation time using the method getCreationTime() and the last access time of this web page using the method getLastAccessedTime().

 

The program then checks if a session is new then it stores the title to be displayed as ” and set the userID to the session. When the next time the servlet is invoked, it displays the title as ” Welcome Back to my website” and sets the visit count to the session object. Every time the page is accessed the visit count is incremented and is set to the session, retrieved and displayed.

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

// Extend HttpServlet class

public class SessionTrack extends HttpServlet

{

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

{

//  Create a session object if it is already not created. HttpSession session = request.getSession(true);

//  Get session creation time.

Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page.

Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = “Welcome Back to my website”;

Integer visitCount = new Integer(0);

String visitCountKey = new String(“visitCount”);

String userIDKey = new String(“userID”);

String userID = new String(“ABCD”);

//  Check if this is new comer on your web page. if (session.isNew())

{

title = “Welcome to my website”;

session.setAttribute(userIDKey, userID);}

else

{

visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1;userID = String)session.getAttribute(userIDKey);

}

session.setAttribute(visitCountKey, visitCount);

//  Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter();

String docType = “<!doctype html public \”-//w3c//dtd html 4.0 ” + “transitional//en\”>\n”;

out.println(docType + “<html>\n” + “<head><title>” + title + “</title></head>\n” +“<body bgcolor=\”#f0f0f0\”>\n” +“<h1 align=\”center\”>” + title + “</h1>\n” +“<h2 align=\”center\”>Session Information</h2>\n” + “<table border=\”1\” align=\”center\”>\n” + “<tr bgcolor=\”#949494\”>\n” +”  <th>Session info</th><th>value</th></tr>\n” + “<tr>\n” +”  <td>id</td>\n” + ” <td>” + session.getId() + “</td> </tr>\n” +“<tr>\n” +”  <td>Creation Time</td>\n” +  ” <td>” + createTime +”  </td></tr>\n” +“<tr>\n” +”  <td>Time of Last Access</td>\n” + ” <td>” + lastAccessTime +”  </td></tr>\n” +“<tr>\n” +”  <td>User </td>\n” + ” <td>” + userID + ” </td> </tr>\n” +“<tr>\n” +”  <td>Number of visits</td>\n” + ” <td>” + visitCount + “</td></tr>\n” + “</table>\n” + “</body></html>”); } }

     Output

 

Welcome to my website

Session Information

 

Servlet with JDBC

 

Servlets can communicate with databases via JDBC (Java Database Connectivity). JDBC provides a uniform way for a Java program to connect with a variety of databases in a general manner without having to deal with the specifics of those database systems.

 

Example

 

This example program demonstrates the design of an HTML form to get the Name and RollNo from the user whose value will be retrieved in a Servlet program and stored in the database.

 

<html>

<body>

<form  method = “get” action= “http:\\127.0.0.1:8080\servlet-html\Servlet_jdbc.html”>

Name <input type=input name=”Name” value=””> <br>

RollNo <input type=input name=”RollNo” value=””> <br>

<input type=submit value=”submit”>

</form>

</body>

</html>

 

Example: Establishing JDBC connection

 

This example illustrate a simple Servlet JDBC program that gets the RollNo and Name from the client and store it in a database.Initially the Servlet retrieves the information from the HTML page using the getParameter() method.

To establish JDBC connection, we need to dynamically load and register the driver. Then establish a connection by creating a Connection object using the DriverManager class. Then use the method executeUpdate() to insert the retrieved values into the database. and executeQuery() to display the values from the database.

 

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Servlet_jdbc extends HttpServlet {

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException ,IOException

{

res.setContentType(“text/html”);

PrintWriter out = res.getWriter();

String str1=req.getParameter(“Name”);

String str2=req.getParameter(“RollNo”);

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Connection con=DriverManager.getConnection(“jdbc:odbc:test”);

Statement st=con.createStatement();

String query=”select * from student”;

String q2 = “insert into student values (‘” + str1 + “‘,” + str2 + “)”;

st.executeUpdate(q2);

ResultSet rs=st.executeQuery(query);

while(rs.next())

{

out.println(rs.getString(“Name”)); //getString()

out.println(rs.getInt(“RollNo”));//getInt()

}

con.close();

}

catch(Exception e)

{

}

out.println(“Submission Successful”);

}

    Output: Servlet with JDBC

 

The output of this Servlet JDBC program is shown in Figure 32.4 and Figure 32.5.

 

      Example: Servlet with JDBC

 

This is an another example to demonstrate about Servlet with JDBC. We design the HTML page in which the user inputs the information such as Database driver name, Database name, User name, Password and Query to execute.

 

When the servlet is invoked, the first step is to load and register the driver using database driver name. Then the connection is established using the database name, username and password. Then the servlet checks if the query string is a “Select” query, and if so it executes the query using the method executeQuery() that returns the ResultSet object. From the ResultSet object, it uses the method getMetaData() to return a ResultSetMetaData object. Using this ResultSetMetaData object we can get the column count using the method getColumnCount(). Then use a for loop and retrieve the column name using the method getColumnName() and the values stored in the column to display the records from the database. If the query string is not a “Select” query then the method executeUpdate() is used to execute the query string which returns the number of rows affected by the query statement which is displayed to the user.

 

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class DemoServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{

response.setContentType(“text/html;charset=UTF-8”);

try (PrintWriter out = response.getWriter())

{

out.println(“<!DOCTYPE html>”);

out.println(“<html>”);

out.println(“<head>”);

out.println(“<title>Servlet DemoServlet</title>”);

out.println(“</head>”);

out.println(“<body>”);

String db_driver=request.getParameter(“driv”);

String db_name=request.getParameter(“ur”);

String db_uname=request.getParameter(“uname”);

String db_pwd=request.getParameter(“pwd”);

String db_query=request.getParameter(“qry”);

try

{

Class.forName(db_driver);

Connection  connection=DriverManager.getConnection(“jdbc:mysql://localhost:3306/“+db_name,db_uname,db_pwd);

Statement stmt=connection.createStatement(); String q=db_query;

String first_word=q.split(” “)[0];

if(first_word.equals(“Select”)||first_word.equals(“select”)||first_word.equa ls(“SELECT”))

{

ResultSet rs=stmt.executeQuery(q);

ResultSetMetaData rsmd=rs.getMetaData();

int columncount=rsmd.getColumnCount(); out.println(“<TABLE BORDER=1 ALIGN=’CENTER’>”); if(columncount>=1)

{

out.println(“<TR>”);

for(int i=1;i<=columncount;i++)

{

out.println(“<TH>”+rsmd.getColumnName(i));

}

out.println();

while(rs.next())

{

out.println(“<TR>”);

for(int i=1;i<=columncount;i++)

{

out.println(“<TD>”+rs.getString(i));

}

out.println();

}

out.println(“</TABLE>”);

connection.close();

}

else

{

out.println(“<h1>No Records found!</h1>”); connection.close();

}

}else

{

int ers=stmt.executeUpdate(q); if(ers>0)

{

out.println(“<h1>Statement Executed! “+ers+” rows affected</h1>”);

}

else

{

out.println(“<h1>Statement Executed and 0 rows affected!</h1>”);

}

connection.close();

}

}

catch(ClassNotFoundException cnfe)

{

System.err.println(“Error Loading Driver:”+cnfe);

}

Catch(SQLException sqle)

{

System.err.println(“Error Connecting:”+sqle);

}

catch(Exception ex)

{

System.err.println(“Error with Input:”+ex);

}

out.println(“</body>”);

out.println(“</html>”);

}

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

Protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

}

  Summary

 

In this module we have discussed about Session Tracking in Java HttpSession API. We looked into the basic explanation with Simple examples of how to work with Session tracking. This section have also covered an idea of how to use Servlets with JDBC with examples. Thus an easier learning of establishing database connectivity with Servlets has been done with the help of illustrations in this section.

 

Web Links

  • Herbert Schildt, ” Java: The Complete Reference”, 9th Edition, Mcgraw-Hill, 2014.
  • http://www.tutorialspoint.com