1 of 17

Cookies in JSP

2 of 17

Introduction

Cookies are text files stored on the client computer and they are kept for various information tracking purposes. JSP transparently supports HTTP cookies using underlying servlet technology.

There are three steps involved in identifying and returning users

  • Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc.
  • Browser stores this information on the local machine for future use.
  • When the next time the browser sends any request to the web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well.

3 of 17

Servlet Cookies Methods

Name

Description

public void setDomain(String pattern)

This method sets the domain to which the cookie applies;

for example, Google.com.

public String getDomain()

This method gets the domain to which the cookie applies; for example, Google.com.

public void setMaxAge(int expiry)

This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.

public int getMaxAge()

This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until the browser shutdown.

public String getName()

This method returns the name of the cookie. The name cannot be changed after the creation.

public void setValue(String newValue)

This method sets the value associated with the cookie.

public String getValue()

This method gets the value associated with the cookie.

4 of 17

Setting Cookies with JSP

  • Setting cookies with JSP involves three steps 

Step 1: Creating a Cookie object

  • You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Step 2: Setting the maximum age

  • You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

Step 3: Sending the Cookie into the HTTP response headers

  • You use response.addCookie to add cookies in the HTTP response header as follows

response.addCookie(cookie);

5 of 17

<%

Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));

Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

firstName.setMaxAge(60*60*24);

lastName.setMaxAge(60*60*24);

response.addCookie( firstName );

response.addCookie( lastName );

%>

<html>

<head>

<title>Setting Cookies</title>

</head>

<body>

<center>

<h1>Setting Cookies</h1>

</center>

<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>

6 of 17

<html>

<body>

<form action = "main.jsp" method = "GET">

First Name: <input type = "text" name = "first_name"> <br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" /> </form> </body>

</html>

7 of 17

Sessions in JSP

  • session is an implicit object
  • In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to set,get or remove attribute or to get session information.

This interface provides a way to identify a user across.

  1. a one page request or
  2. visit to a website or
  3. store information about that user
  4. By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −
  5. <%@ page session = "false" %>

8 of 17

Session Tracking in JSP

  • 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.
  • Session tracking is a mechanism that is used to maintain state about a series of requests from the same user(requests originating from the same browser) across some period of time. A session id is a unique token number assigned to a specific user for the duration of that user's session.
  • HTTP is stateless that means each request is considered as the new request.

9 of 17

Session Tracking Techniques

There are four techniques used in Session tracking:

  • Cookies
  • Hidden Form Field
  • URL Rewriting
  • HttpSession

10 of 17

  • Cookies mostly used for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie.
  • This is not an effective way because many time browser does not support a cookie or users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

11 of 17

URL Rewriting :

  • Here is a simple URL which will pass two values using GET method.You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.For Example Original URL:http://javwebtutor.com/jsp/name Rewritten URL: http://javawebtutor.com/jsp/name?sessionid=12345 .When a request is made an additional parameter is appended with the url.sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client.

12 of 17

Hidden Form Fields

  • HTML forms have an entry that looks like <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

13 of 17

The session Object :

  • Servlets provided HttpSession Interface will provides a way to identify a user across multiple request to a Web site and to store information about that user.
  • For JSPs, by default a session is automatically created for the request if one does not exist. So if your starting page is a JSP, a session would have already been created when you get the first request.

14 of 17

Connecting to Database using JSP

  • Create Table-To create the Employees table in the EMP database,

Step 1:Open a Command Prompt and change to the installation directory as follows

C:\> C:\>cd Program Files\MySQL\bin

C:\Program Files\MySQL\bin>

Step 2:Login to the database as follows

C:\Program Files\MySQL\bin>mysql -u root -p

Enter password: ******** mysql>

15 of 17

  • Step 3:Create the Employee table in the TEST database as follows

mysql> use TEST;

mysql> create table Employees

( id int not null, age int not null, first varchar (255), last varchar (255) );

Query OK, 0 rows affected (0.08 sec)

mysql>

Step4: Create Data Records: Let us now create a few records in the Employee table as follows

mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec)

mysql>

16 of 17

SELECT Operation using JSP

<%@ page import = "java.io.*,java.util.*,java.sql.*"%>

<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>

<html>

<head>

<title>SELECT Operation</title>

</head>

<body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/>

<sql:query dataSource = "${snapshot}" var = "result">

SELECT * from Employees;

</sql:query>

<table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr>

<c:forEach var = "row" items = "${result.rows}"> <tr> <td><c:out value = "${row.id}"/></td> <td><c:out value = "${row.first}"/></td> <td><c:out value = "${row.last}"/></td> <td><c:out value = "${row.age}"/></td> </tr> </c:forEach> </table> </body> </html>

17 of 17

Output