JSP - WordPress.com

Download Report

Transcript JSP - WordPress.com

JSP
Java Server Pages
Apr 3, 2013
A “Hello World” servlet
(from the Tomcat installation documentation)
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
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>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>Hello World</H1>\n" +
"</BODY></HTML>");
}
This is mostly Java with a little HTML mixed in
}
2
HelloWorld
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello CS764!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello CS764!</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
Servlets


The purpose of a servlet is to create a Web page in response to a
client request
Servlets are written in Java, with a little HTML mixed in


JSP (Java Server Pages) is an alternate way of creating servlets




JSP is written as ordinary HTML, with a little Java mixed in
The Java is enclosed in special tags, such as <% ... %>
The HTML is known as the template text
JSP files must have the extension .jsp




The HTML is enclosed in out.println( ) statements
JSP is translated into a Java servlet, which is then compiled
Servlets are run in the usual way
The browser or other client sees only the resultant HTML, as usual
Tomcat knows how to handle servlets and JSP pages
4
JSP Introduction
• JavaServer Pages (JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-based
applications.
• JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise databases.
• JavaServer Pages (JSP) is a technology for developing
web pages that support dynamic content which helps
developers insert java code in HTML pages by making
use of special JSP tags, most of which start with <% and
end with %>.
Why Use JSP?
• Performance is significantly better because JSP allows
embedding Dynamic Elements in HTML Pages itself
instead of having a separate CGI files.
• JSP are always compiled before it's processed by the server
(unlike CGI/Perl which requires the server to load an
interpreter and the target script each time the page is
requested.)
• JavaServer Pages are built on top of the Java Servlets API,
so like Servlets, JSP also has access to all the powerful
Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP
etc.
• JSP pages can be used in combination with servlets that
handle the business logic
JSP - Architecture
JSP Processing
JSP life cycle
JSP life cycle
JSP Initialization: When a container loads a JSP it invokes
the jspInit() method before servicing any requests.
public void jspInit(){ // Initialization code... }
JSP Execution: This phase of the JSP life cycle represents all
interactions with requests until the JSP is destroyed.
void _jspService(HttpServletRequest request,
HttpServletResponse response) { // Service handling code... }
JSP Cleanup: The destruction phase of the JSP life cycle
represents when a JSP is being removed from use by a
container.
public void jspDestroy() { // Your cleanup code goes here. }
The Scriptlet
A scriptlet can contain any number of JAVA language
statements, variable or method declarations, or
expressions that are valid in the page scripting language.
Syntax of Scriptlet:
<% code fragment %>
<jsp:scriptlet> code fragment </jsp:scriptlet>
Example:
<html> <head><title>Hello World</title></head>
<body> Hello World!<br/>
<% out.println(“Welcome to JSP”) %> </body> </html>
JSP Declarations:
A declaration declares one or more variables or methods
that you can use in Java code later in the JSP file.
You must declare the variable or method before you use it
in the JSP file.
Syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>
<jsp:declaration> code fragment </jsp:declaration>
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression:
A JSP expression element contains a scripting language
expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file.
<%= expression %>
<jsp:expression> expression </jsp:expression>
Example:
<html> <head><title>A Comment Test</title></head>
<body> <p> Today's date: <%= (new
java.util.Date()).toLocaleString()%> </p> </body>
</html> Result:
Today's date: 11-Sep-2010 21:24:25
JSP Comments:
JSP comment marks text or statements that the JSP
container should ignore.
Syntax:
<%-- This is JSP comment --%>
Example:
<html> <head><title>A Comment Test</title></head>
<body> <h2>A Test of Comments</h2> <%-- This
comment will not be visible in the page source --%>
</body> </html>
JSP scripting elements

<%= expression %>


<% code %>



The expression is evaluated and the result is inserted into the HTML page
The code is inserted into the servlet's service method
This construction is called a scriptlet
<%! declarations %>

The declarations are inserted into the servlet class, not into a method
15
JSP Tags Examples
Comments <%-- …...text…... --%>
Declaration <%! int i; %>
<%! int numOfStudents(arg1,..) {} %>
Expression <%= 1+1 %>
Scriptlets <% … java code … %>
include file <%@ include file=“*.jsp” %>
…...
Example JSP


<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Notes:


The <%= ... %> tag is used, because we are computing a
value and inserting it into the HTML
The fully qualified name (java.util.Date) is used, instead of
the short name (Date), because we haven’t yet talked about
how to do import declarations
17
Variables


You can declare your own variables, as usual
JSP provides several predefined variables





request : The HttpServletRequest parameter
response : The HttpServletResponse parameter
session : The HttpSession associated with the request, or
null if there is none
out : A JspWriter (like a PrintWriter) used to send output
to the client
Example:

Your hostname: <%= request.getRemoteHost() %>
18
A First JSP
<html>
<head></head>
<body>
<p>Enter two numbers and click the
‘calculate’ button.</p>
<form action=“calculator.jsp” method=“get”>
<input type=text name=value1><br>
Calculator.html
<input type=text name=value2 ><br>
<input type=submit name=calculate value=calculate>
</form>
</body>
</html>
<html>
<head><title>A simple calculator: results</title></head>
<body>
<%-- A simpler example 1+1=2 --%>
1+1 = <%= 1+1 %>
<%-- A simple calculator --%>
<h2>The sum of your two numbers is:</h2>
<%= Integer.parseInt(request.getParameter("value1")) +
Integer.parseInt(request.getParameter("value2")) %>
</body>
</html>
Calculator.jsp
Scriptlets

Scriptlets are enclosed in <% ... %> tags




Scriptlets do not produce a value that is inserted directly into the
HTML (as is done with <%= ... %>)
Scriptlets are Java code that may write into the HTML
Example:
<% String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData); %>
Scriptlets are inserted into the servlet exactly as written,
and are not compiled until the entire servlet is compiled

Example:
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
21
Declarations

Use <%! ... %> for declarations to be added to your
servlet class, not to any particular method





Caution: Servlets are multithreaded, so nonlocal variables
must be handled with extreme care
If declared with <% ... %>, variables are local and OK
Data can also safely be put in the request or session objects
Example:
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
You can use <%! ... %> to declare methods as easily as
to declare variables
22
Exception handling in JSP
• These are nothing but the abnormal conditions which
interrupts the normal flow of execution.
• Mostly they occur because of the wrong data entered by
user.
• It is must to handle exceptions in order to give
meaningful message to the user
• So that user would be able to understand the issue and
take appropriate action.
Exception handling using
exception implicit object
Index.jsp
<%@ page errorPage="errorpage.jsp" %>
<html> <head>
<title>JSP exception handling example</title> </head>
<body> <% //Declared and initialized two integers int
num1 = 122;
int num2 = 0;
//It should throw Arithmetic Exception
int div = num1/num2; %>
</body> </html>
Errorpage.jsp
<%@ page isErrorPage="true" %> <html>
<head> <title>Display the Exception Message
here</title> </head>
<body> <h2>errorpage.jsp</h2>
<i>An exception has occurred in the index.jsp Page.
Please fix the errors. Below is the error message:</i>
<b>
<%= exception %></b>
</body>
</html>
Exception handling using try
catch blocks within scriptlets
Error.jsp
<html> <head> <title>Exception handling using try catch
blocks</title>
</head> <body> <% try
{ //I have defined an array of length 5 int
arr[]={1,2,3,4,5};
int num=arr[6];
out.println("7th element of arr"+num); }
catch (Exception exp){ out.println("There is something
wrong: " + exp); } %>
</body> </html>
JSP Directives
• JSP directives provide directions and instructions
to the container, telling it how to handle certain
aspects of JSP processing.
• A JSP directive affects the overall structure of
the servlet class. It usually has the following
form:
• <%@ directive attribute="value" %>
Directive Types
DirectiveDescription
<%@ page ... %>Defines page-dependent
attributes, such as scripting language, error page,
and buffering requirements.
<%@ include ... %>Includes a file during the
translation phase.
<%@ taglib ... %>Declares a tag library,
containing custom actions, used in the page
Directives



Directives affect the servlet class itself
A directive has the form:
<%@ directive attribute="value" %>
or
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
The most useful directive is page, which lets you
import packages

Example: <%@ page import="java.util.*" %>
29
The page Directive
• The page directive is used to provide
instructions to the container that pertain to the
current JSP page.
• Code page directives anywhere in your JSP page.
• By convention, page directives are coded at the
top of the JSP page.
Syntax of page directive:
<%@ page attribute="value" %>
<jsp:directive.page attribute="value" />
Page Directive Attribute
•
•
•
•
•
•
•
•
•
•
•
import
session
isErrorPage
errorPage
ContentType
isThreadSafe
extends
info
language
autoflush
buffer
Page Directive Example
<%@ page import="java.util.*" %>
<HTML> <BODY>
<% System.out.println( "Evaluating date now" );
Date date = new Date(); %>
Hello! The time is now <%= date %>
</BODY>
</HTML>
The taglib Directive
• The JavaServer Pages API allows you to define custom
JSP tags that look like HTML or XML tags
• A tag library is a set of user-defined tags that implement
custom behavior.
The taglib directive declares that your JSP page uses a set
of custom tags, identifies the location of the library, and
provides a means for identifying the custom tags in your
JSP page.
Syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
JSP Taglib Example
The custlib tag library contains a tag called hello.
If you wanted to use the hello tag with a prefix of mytag,
your tag would be<mytag:hello>
Code:
<%@ taglib uri="http://www.example.com/custlib"
prefix="mytag" %> <html> <body>
<mytag:hello/> </body>
</html>
The include directive

The include directive inserts another file into the file
being parsed


Syntax: <%@ include file="URL " %>



The included file is treated as just more JSP, hence it can
include static HTML, scripting elements, actions, and
directives
The URL is treated as relative to the JSP page
If the URL begins with a slash, it is treated as relative to the
home directory of the Web server
The include directive is especially useful for inserting
things like navigation bars
35
JSP Include Directive Example
Index.jsp
<html> <head> <title>Passing Parameters to Include
directive</title>
</head> <body>
<%@ include file="file1.jsp" %>
<%! String country="India";
String state="UP";
String city="Agra"; %>
<% session.setAttribute("co", country);
session.setAttribute("st", state);
session.setAttribute("ci", city); %> </body> </html>
Output
File1.jsp
<%=session.getAttribute("co") %>
<%=session.getAttribute("st") %>
<%=session.getAttribute("ci") %>
Output:
India UP Agra
Actions


Actions are XML-syntax tags used to control the servlet
engine
<jsp:include page="URL " flush="true" />



Inserts the indicated relative URL at execution time (not at
compile time, like the include directive does)
This is great for rapidly changing data
<jsp:forward page="URL" />
<jsp:forward page="<%= JavaExpression %>" />

Jump to the (static) URL or the (dynamically computed)
JavaExpression resulting in a URL
38
Directives vs Actions
• Directives are used during translation phase while
actions are used during request processing phase.
• Unlike Directives Actions are re-evaluated each time
the page is accessed.
JSP Forward Example 1 –
without passing parameters
Index.jsp Contains
<html> <head> <title>JSP forward action tag
example</title> </head> <body> <p align="center">My
main JSP page</p>
<jsp:forward page="display.jsp" /> </body> </html>
display.jsp
<html> <head> <title>Display Page</title>
</head> <body> Hello this is a display.jsp Page
</body> </html>
JSP Forward Example 2 – with
parameters
Index.jsp
<html> <head>
<title>JSP forward example with parameters</title>
</head> <body>
<jsp:forward page="display.jsp">
<jsp:param name="name" value="Chaitanya" />
<jsp:param name="site" value="BeginnersBook.com" />
<jsp:param name="tutorialname" value="jsp forward
action" />
<jsp:param name="reqcamefrom" value="index.jsp" />
</jsp:forward> </body> </html>
Display.jsp
<html> <head> <title>Display Page</title> </head>
<body>
<h2>Hello this is a display.jsp Page</h2>
My name is: <%=request.getParameter("name") %><br>
Website: <%=request.getParameter("site") %><br>
Topic: <%=request.getParameter("tutorialname") %><br>
Forward Request came from the page:
<%=request.getParameter("reqcamefrom") %>
</body>
</html>
<jsp:include> Action
• include page directive this action is also used to insert
a JSP file in another file.
Syntax of <jsp:include> :
<jsp:include page="page URL" flush="Boolean Value" />
Example:
<html> <head>
<title>Demo of JSP include Action Tag</title> </head>
<body> <h3>JSP page: Demo Include</h3>
<jsp:include page="sample.jsp" flush="false" />
</body> </html>
<jsp:forward> Action
• <jsp:forward> is used for redirecting the request.
• When this action is encountered on a JSP page the
control gets transferred to the page mentioned in this
action.
Syntax of <jsp:forward> :
<jsp:forward page="URL of the another static, JSP OR
Servlet page" />
Example
<html> <head>
<title>Demo of JSP Forward Action Tag</title> </head>
<body> <h3>JSP page: Demo forward</h3>
<jsp:forward page="second.jsp" />
</body>
</html>
<jsp:param> Action
• This action is useful for passing the parameters to Other
JSP action tags such as JSP include & JSP forward tag.
• This way new JSP pages can have access to those
parameters using request object itself.
• Syntax of <jsp:param>:
<jsp: param name="param_name_here"
value="value_of_parameter_here" />
First.jsp
<html> <head> <title>Demo of JSP Param Action
Tag</title> </head> <body> <h3>JSP page: Demo
Param along with forward</h3>
<jsp:forward page="second.jsp">
<jsp:param name ="date" value="20-05-2012" />
<jsp:param name ="time" value="10:15AM" />
<jsp:param name ="data" value="ABC" />
</jsp:forward>
</body> </html>
Second File:
Date:<%= request.getParameter("date") %>
Time:<%= request.getParameter("time") %> My
Data:<%= request.getParameter("data") %>
<jsp:useBean> Action
This action is useful when you want to use Beans in a JSP
page, through this tag you can easily invoke a bean.
Syntax of <jsp:useBean>:
<jsp: useBean
id="unique_name_to_identify_bean" class="package_n
ame.class_name>
EmployeeTest.jsp
<html> <head> <title>JSP Page to show use of useBean
action</title> </head>
<body> <h1>Demo: Action</h1>
<jsp:useBean id="student"
class="javabeansample.StuBean"/>
<jsp:setProperty name="student" property="*"/>
<h1> name:<jsp:getProperty name="student"
property="name"/>
<br> empno:<jsp:getProperty name="student"
property="rollno"/><br> </h1>
</body> </html>
StudentBean.java
package javabeansample;
public class StuBean {
public StuBean() { }
private String name;
private int rollno;
public void setName(String name) {
this.name=name; }
public String getName() { return name; }
public void setRollno(int rollno) {
this.rollno=rollno; }
public int getRollno() { return rollno; } }
<jsp:plugin> Action
• This tag is used when there is a need of a plugin to run a
Bean class or an Applet.
JSP - Database Access
• Understanding on how JDBC application works.
• Before starting with database access through a JSP,
make sure that you have proper JDBC environment
setup along with a database.
Steps to creatd JDBC
Tables creation
Load the driver manager
Connection establishment
Statement creations
Process the result set
Execute the statement
Close the connection and statement
Stop the program

Creating a Database Table
String table ;
table= "CREATE TABLE Employee11(Emp_code
integer, Emp_name varchar(10))";
st.executeUpdate(table);
Connection Establishment
Is an interface in java.sql package
Specifies connection with specific database like:
MySQL, Ms-Access, Oracle etc and java files.
The SQL statements are executed within the
context of the Connection interface.

Class.forName(String driver):

Connection Establishment
Syntax
Connection conn;
Class.forname(“com.mysql.jdbc.Driver”).newInsta
nce();

DriverManager
It is a class of java.sql package that controls a set of
JDBC drivers.
Each driver has to be register with this class.
getConnection(String url, String userName, String
password):
 url: - Database url where stored or created your
database
 userName: - User name of MySQL
 password: -Password of MySQL

Load the JDBC Driver into the database
Syntax
String userName = "root";
String password = "mysql";
String url =
"jdbc:mysql://localhost/programs";
 conn =
DriverManager.getConnection(url,user
Name,password);

Create the statements and update the
values in the table structure
Statement st=conn.createStatement();
 st.execute("create table stud10(rollno
int,name text,m1 int,m2 int)");
 st.executeUpdate("insert into stud10
values(2,'rani',50,90)");

Process the Query result set
rs=st.executeQuery("select * from stud10");
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getInt(3));
System.out.println(rs.getInt(4));
}
Close the connection
con.close():
This method is used for disconnecting the
connection.
It frees all the resources occupied by the database.

Close the statement and connection


st.close();
conn.close();
Final Steps
To import Syntax
export
CLASSPATH=$CLASSPATH:/usr/share/java/my
sql-connector-java-5.1.6.jar

To Compile
Javac Filename.java
 To Run
java Filename

Error Report
printStackTrace():
The method is used to show error messages. If the
connection is not established then exception is
thrown and print the message.

Create Table
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>
Create Data Records
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)
Connecting JSP To Mysql Database
Login.html
<body>
<form action="login.jsp" method="post">
User name :<input type="text" name="usr" />
password :<input type="password" name="pwd" />
<input type="submit" /></form></body>
Reg.html
<form action="reg.jsp" method="post“>
Email :<input type="text" name="email" />
First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
User name :<input type="text" name="userid" />
password :<input type="password" name="pwd" />
<input type="submit" /></form>
Login.jsp
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<% String userid=request.getParameter("user");
session.putValue("userid",userid);
String pwd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/
test","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where
user_id='"+userid+"'");
if(rs.next()) {
if(rs.getString(2).equals(pwd)) {
out.println("welcome"+userid); } else { out.println("Invalid password
try again"); } } else %>
Reg.jsp
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %><%
String user=request.getParameter("userid");
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values
('"+user+"','"+pwd+"','"+fname+"',
'"+lname+"','"+email+"')");
Index.html
<HTML> <HEAD>
<TITLE>Database Lookup</TITLE> </HEAD>
<BODY> <H1>Database Lookup</H1>
<FORM ACTION="basic.jsp" METHOD="POST">
Please enter the ID of the publisher you want to find:
<BR>
<INPUT TYPE="TEXT" NAME="id"> <BR>
<INPUT TYPE="SUBMIT" value="Submit"> </FORM>
</BODY>
<HTML>
Basic.jsp
<%@ page import="java.sql.*" %>
<% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); %><HTML>
<HEAD> <TITLE>Fetching Data From a Database</TITLE>
</HEAD>
<BODY> <H1>Fetching Data From a Database</H1>
<% Connection connection = DriverManager.getConnection(
"jdbc:odbc:data", "YourName", "password");
Statement statement = connection.createStatement(); String id =
request.getParameter("id");
ResultSet resultset = statement.executeQuery("select * from Publishers
where pub_id = '" + id + "'") ;
if(!resultset.next()) { out.println("Sorry, could not find that publisher. ");
} else { %>
Basic.jsp
<TABLE BORDER="1"> <TR> <TH>ID</TH>
<TH>Name</TH> <TH>City</TH> <TH>State</TH>
<TH>Country</TH> </TR> <TR> <TD>
<%= resultset.getString(1) %> </TD> <TD>
<%= resultset.getString(2) %> </TD> <TD>
<%= resultset.getString(3) %> </TD> <TD>
<%= resultset.getString(4) %> </TD> <TD>
<%= resultset.getString(5) %> </TD> </TR>
</TABLE> <BR> <% } %>
</BODY> </HTML>
JSP in XML






JSP can be embedded in XML as well as in HTML
Due to XML’s syntax rules, the tags must be
different (but they do the same things)
HTML: <%= expression %>
XML: <jsp:expression>expression</jsp:expression>
HTML: <% code %>
XML: <jsp:scriptlet>code</jsp:scriptlet>
HTML: <%! declarations %>
XML: <jsp:declaration>declarations</jsp:declaration>
HTML: <%@ include file=URL %>
XML: <jsp:directive.include file="URL"/>
74
Sending XML from a JSP
<%@ page contentType="text/xml" %>
File Content:
<%@ page contentType="text/xml" %> <books>
<book> <name>Padam History</name>
<author>ZARA</author>
<price>100</price> </book>
</books>
Processing XML in JSP
Books.xml
<books> <book> <name>Padam History</name>
<author>ZARA</author> <price>100</price> </book>
<book> <name>Great Mistry</name>
<author>NUHA</author> <price>2000</price>
</book>
</books>
Formatting XML with JSP
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl= "http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<html> <body> <xsl:apply-templates/> </body> </html>
</xsl:template> <xsl:template match="books">
<table border="1" width="100%">
<xsl:for-each select="book"> <tr>
<td> <i><xsl:value-of select="name"/></i> </td>
<td> <xsl:value-of select="author"/> </td>
<td> <xsl:value-of select="price"/> </td> </tr>
</xsl:for-each> </table> </xsl:template> </xsl:stylesheet>
JSP Session tracking
• Server may be responding to several clients at a time
• So session tracking is a way by which a server can
identify the client.
Session Tracking Techniques
a) Cookies
b) Hidden Fields
c) URL Rewriting
d) Session Object
Cookie
• Cookie is a key value pair of information, sent by the server
to the browser
• The browser sends back this identifier to the server with
every request there on.
Types of cookies:
· Session cookies - are temporary cookies and are deleted as
soon as user closes the browser. The next time user visits
the same website, server will treat it as a new client as
cookies are already deleted.
· Persistent cookies - remains on hard drive until we delete
them or they expire.
Cookie Creation
Cookie cookie = new Cookie(“sessionID”, “some unique value”);
response.addCookie(cookie);
Hidden Field
• Hidden fields are similar to other input fields with the only
difference is that these fields are not displayed on the page
• But its value is sent as other input fields. For example
<input type=”hidden” name=”sessionId” value=”unique
value”/>
• Is a hidden form field which will not displayed to the user
• But its value will be send to the server and can be retrieved
using request.getParameter(“sessionId”) .
URL Rewriting
URL Rewriting is the approach in which a session
(unique) identifier gets appended with each request
URL so server can identify the user session.
For example if we apply URL rewriting on
http://localhost:8080/jsp-tutorial/home.jsp , it will
become something like
?jSessionId=XYZ where
jSessionId=XYZ is the attached session identifier and
value XYZ will be used by server to identify the user
session.
Session Object
• Session object is representation of a user session.
• User Session starts when a user opens a browser and
sends the first request to server.
• Session object is available in all the request (in entire
user session)
• So attributes stored in Http session in will be available
in any servlet or in a jsp
Session Object
How to get a Session Object – By calling getSession()
API on HttpServletRequest object
a) HttpSession session = request.getSession()
b) HttpSession session = request.getSession(Boolean)
Destroy or Invalidate Session –
To invalidate the session use session.invalidate();
Important methods
· Object getAttribute(String attributeName) – this method
is used to get the attribute stored in a session scope by
attribute name. Remember the return type is Object.
· void setAttribute(String attributeName, Object value)this method is used to store an attribute in session scope.
This method takes two arguments- one is attribute name and
another is value.
· void removeAttribute(String attributeName)- this method
is used to remove the attribute from session.
· public boolean isNew()- This method returns true if server
does not found any state of the client.
JSP Session Tracking Examples
<html>
<head> <title> Display Session Information </title> </head>
%@page import="java.util.Date" % <body>
<%
long creationTime = session.getCreationTime();
String sessionId = session.getId();
long lastAccessedTime = session.getLastAccessedTime();
Date createDate= new Date(creationTime);
Date lastAccessedDate= new Date(lastAccessedTime);
StringBuffer buffer = new StringBuffer();
if(session.isNew())
else
{
{
buffer.append("<h3>Welcome </h3>");
buffer.append("<h3>Welcome Back!! </h3>");
buffer.append("<STRONG> Session ID : </STRONG>" + sessionId);
<BR/> ");
}
}
buffer.append("
buffer.append("<STRONG> Session Creation Time </STRONG>: " + createDate);
buffer.append(" <BR/> "); buffer.append("<STRONG> Last Accessed Time : </STRONG>"
+ lastAccessedDate);
buffer.append(" <BR/> ");
%>
<%=
buffer.toString()
%>
</body> </html>
Output
The End
88