Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit-4 JSP - Notes - WT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Web Technologies Unit-4

UNIT- 4
JSP
(Java Server Pages)
CONTENT:
UNIT – IV

Introduction to JSP: The Anatomy of a JSP Page, JSP Processing,


Declarations, Directives, Expressions, Code Snippets, implicit objects, Using
Beans in JSP Pages, Using Cookies and session for session tracking, connecting
to database in JSP.

SUBJECT FACULTY: RAPOLU SATHEESH


BRANCH/YEAR/SEM: CSE/III/I
REGULATION: R18

1|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

UNIT- 4 : JSP

3.1 INTRODUCTION TO JSP


JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfil the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database
or registering user preferences, accessing JavaBeans components, passing control between
pages, and sharing information between requests, pages etc.

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.

Why should we Learn JSP?


There are numerous reasons for us to learn JSP.

1) Its extension to Servlet technology will be the very first reason to learn JSP. In JSP, we can
use all the functionality of Servlet. In addition, speech-language, predefined tags, implicit
entities and custom tags can be used in JSP, making it easier for JSP to create.

2) The second reason would be that there is no need to redeploy and recompile the project in
case the JSP page is modified. If we have to modify the look and sound of the programme, the
Servlet code has to be revised and recompiled.

3) Third would be about how easy JSP is to maintain and manage as we can conveniently
separate the presentation and business logic.

2|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

4) In JSP, we can use several tags which reduce the code, such as action tags, JSTL, custom
tags, etc. We may, in addition, use EL, implied objects, etc.

Advantages of JSP over Servlet

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP.
In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in
JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation
logic. In Servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

3|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating the
JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted
into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later
like initialization, committing response to the browser and destroy.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:

4|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

JSP Declaration
The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.

index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.

5|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as well
not methods. as methods.

The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
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


1. <%@ directive attribute="value" %>
JSP page directive

The page directive defines attributes that apply to an entire JSP page.

6|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

Syntax of JSP page directive


1. <%@ page attribute="value" %>

import
The import attribute is used to import class,interface or all the members of a package.It is similar to import
keyword in java class or interface.

Example of import attribute


1. <html>
2. <body>
3. <%@ page import="java.util.Date" %>
4. Today is: <%= new Date() %>
5. </body>
6. </html>

Jsp 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).

Advantage of Include directive


Code Reusability

Syntax of include directive


1. <%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the header.html file. To run this example you
must create an header.html file.

1. <html>
2. <body>
3. <%@ include file="header.html" %>
4. Today is: <%= java.util.Calendar.getInstance().getTime() %>
5. </body>

7|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

6. </html>

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

Syntax JSP Taglib directive


1. <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive

In this example, we are using our tag named currentDate. To use this tag we must specify the
taglib directive so the container may get information about the tag.

1. <html>
2. <body>
3. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
4. <mytag:currentDate/>
5. </body>
6. </html>

Expressions in JSP

The expression tag is used to evaluate Java's expression within the JSP, which then converts the result
into a string and forwards the result back to the client browser via the response object. Essentially, it
is implemented for printing the result to the client (browser). An expression tag can hold any java
language expression that can be employed as an argument to the out.print() method.

The syntax of the expression tag in JSP looks something like:


Syntax:

<%= expression %>

8|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

This is how the JSP container sees this when it encounters the above expression:
<%= (6*4) %>

It turns out to be:

out.print((6*4));

Example :

<!DOCTYPE html>
<html>
<head>
<title>Expression Tag in JSP</title>
</head>
<% int rollNo = 02; %>
<body>
The next roll number is: <%= ++rollNo %>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<% int g = 60; int k = 40; int r = 20; %>
<%= g+k+r %>
</body>
</html>
Example:
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GeeksforGeeks</title>
</head>

<body>
<% out.println("Hello guys do some addition "); %> <!-- Sriptlet Tag-->
<% int n1=10; int n2=30; %><!-- Sriptlet Tag-->
<% out.println("<br>sum of n1 and n2 is "); %> <!-- Sriptlet Tag-->
<%= n1+n2 %> <!-- Expression tag -->
</body>

9|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

</html>

Code Snippet in JSP

Snippet is a programming term for a small region of re-usable source code, machine code,
or text. Ordinarily, these are formally defined operative units to incorporate into
larger programming modules. Snippet management is a feature of some text editors,
program source code editors, IDEs, and related software.

Also, how do you use code snippets? With a code file open in the editor, choose Snippets >
Insert Snippet from the right-click menu, then My Code Snippets. You should see
a snippet named Square Root. Double-click it. The snippet code is inserted in the code file.

Likewise, people ask, what is code snippet in Java?

A snippet is a small section of text or source code that can be inserted into the code of a
program or Web page. Snippets used in software programming often contain one or more
functions written in C, Java, or another programming language.

What is the output of the code snippet?

Code snippets. A code snippet is boilerplate code which is code that can be used without
changing it. When a candidate writes code, it is evaluated using input (STDIN)
and output (STDOUT). STDIN: The default source of providing input to any computer
program.

JSP Implicit Objects


Implicit objects are a set of Java objects that the JSP Container makes available to
developers on each page. These objects may be accessed as built-in variables via
scripting elements and can also be accessed programmatically by JavaBeans and
Servlets.JSP provide you Total 9 implicit objects which are as follows
1. request:
This is the object of HttpServletRequest class associated with the
request.

2. response:
This is the object of HttpServletResponse class associated with the
response to the client.

10 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

3. config: This is the object of ServletConfig class associated with the page.

4. application: This is the object of ServletContext class associated with the


application context.

5. session: This is the object of HttpSession class associated with the


request.

6. page context: This is the object of PageContext class that encapsulates


the use of server-specific features. This object can be used to find, get or
remove an attribute.

7. page object: The manner we use the keyword this for current object, page
object is used to refer to the current translated servlet class.

8. exception: The exception object represents all errors and exceptions which
is accessed by the respective jsp. The exception implicit object is of
type java.lang.Throwable.

9. out: This is the PrintWriter object where methods like print and println
help for displaying the content to the client.

Request Object:

 A request object is an implicit object that is used to request an implicit object, which
is to receive data on a JSP page, which has been submitted by the user on the
previous JSP/HTML page.
 The request implicit object used in Java is an instance of
a javax.servlet.http.HttpServletRequest interface where a client requests a page
every time the JSP engine has to create a new object for characterizing that request.
 The container creates it for every request.
 It is used to request information such as parameters, header information, server
names, cookies, and HTTP methods.
 It uses the getParameter() method to access the request parameter.

Here is an example of a JSP request implicit object where a user submits login information,
and another JSP page receives it for processing:

11 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

Html file:

<!DOCTYPE html>
<html>
<head>
<title>Please insert a User name and a password</title>
</head>
<body>
<form action="login.jsp">
Please insert Username: <input type="text" name="u_name" /> <br />
Please insert Password: <input type="text" name="passwd" /> <br />
<input type="submit" value="Submit Details" />
</form>
</body>
</html>

Login.jsp file

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


<%
String username = request.getParameter("u_name");
String password = request.getParameter("passwd");
out.print("Name: "+username+" Password: " +passwd);
%>
response object
This is the HttpServletResponse object associated with the response to the client.
The response object also defines the interfaces that deal with creating new HTTP
headers. Through this object the JSP programmer can add new cookies or date
stamps, HTTP status codes, etc.

Html page

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

12 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

</head>

<body>

<%

String name=request.getParameter("username");

out.print("Welcome "+ name);

%>

</body>

</html>

In JSP the response object is implicitly defined, so you don’t have to create an
object. JSP response object is created by the web container for each request of the
client. It basically is used for redirecting to any other resource.
In the below example we use the response object to send the user on Geeksforgeeks
homepage.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GeeksforGeeks</title>
</head>
<body>
<%
//below line in JSP redirect you to geeksforgeeks page
response.sendRedirect("geeksforgeeks.org");
%>
</body>
</html>

Out object

 An out object is an implicit object for writing data to the buffer and sending output as
a response to the client's browser.
 The out implicit object is an instance of a javax.servlet.jsp.jspWriter class.
 You will learn more about the various concepts of the out Object in subsequent
chapters.
Example (HTML file):
<!DOCTYPE html>
<html>

13 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

<head>
<title>Please insert a User name and a password</title>
</head>
<body>
<% out.println("Today's date-time: "+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Session object

 A session object is the most commonly used implicit object implemented to store user
data to make it available on other JSP pages until the user's session is active.
 The session implicit object is an instance of
a javax.servlet.http.HttpSession interface.
 This session object has different session methods to manage data within the session
scope.
 You will learn more about the use of the session in subsequent chapters.

exception object

 An exception implicit object is implemented to handle exceptions to display error


messages.
 The exception implicit object is an instance of the java.lang.Throwable class.
 It is only available for JSP pages, with the isErrorPage value set as "True". This
means Exception objects can only be used in error pages.
Html file:

<!DOCTYPE html>
<html>
<head>
<title>Enter two Integers for Division</title>
</head>
<body>
<form action="submit.jsp">
Insert first Integer: <input type="text" name="numone" /><br />
Insert second Integer: <input type="text" name="numtwo" /><br />
<input type="submit" value="Get Results" />
</form>
</body>

</html>

14 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

Submit.jsp file

<%@ page errorPage="exception.jsp" %>

<%
String num1 = request.getParameter("numone");
String num2 = request.getParameter("numtwo");
int var1= Integer.parseInt(num1);
int var2= Integer.parseInt(num2);
int r= var1 / var2;
out.print("Output is: "+ r);

%>

Exception.jsp

<%@ page isErrorPage='true' %>

<%
out.print("Error Message : ");
out.print(exception.getMessage());

%>

Using Beans in JSP:


A JavaBean is a specially constructed Java class written in the Java and coded according to
the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes

 It provides a default, no-argument constructor.
 It should be serializable and that which can implement the Serializable interface.
 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class –

15 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

S.No. Method & Description

getPropertyName()
1
For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.

setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute will
have only a setPropertyName() method.

JavaBeans Example

Consider a student class with few properties –


package com.student;

public class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;

public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;

16 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

}
}

Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used
in the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on
your requirement. The value of the id attribute may be any value as a long as it is a unique
name among other useBean declarations in the same JSP.
Following example shows how to use the useBean action −
<html>
<head>
<title>useBean Example</title>
</head>

<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing JavaBeans Properties

Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the
get methods and the <jsp:setProperty/> action to access the set methods. Here is the full
syntax −
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>

The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should
be invoked.

17 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>

<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>

<p>Student First Name:


<jsp:getProperty name = "students" property = "firstName"/>
</p>

<p>Student Last Name:


<jsp:getProperty name = "students" property = "lastName"/>
</p>

<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>

</body>
</html>

Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed –

Student First Name: Zara

Student Last Name: Ali

Student Age: 10

18 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

Using cookies and session for session tracking in JSP

Maintaining Session Between Web Client And Server


Let us now discuss a few options to maintain the session between the Web Client and the Web
Server −

Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not
recommended to use this procedure to maintain the sessions.

Hidden Form Fields


A web server can send a hidden HTML form field along with a unique session ID as follows

<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or the POST data. Each time the web browser sends the
request back, the session_id value can be used to keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also
cannot support general session tracking.

URL Rewriting
You can append some extra data at the end of each URL. This data identifies the session; the
server can associate that session identifier with the data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session
identifier is attached as sessionid = 12345 which can be accessed at the web server to identify
the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they
don't support cookies. The drawback here is that you will have to generate every URL
dynamically to assign a session ID though page is a simple static HTML page.
The session Object
Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession
Interface. This interface provides a way to identify a user across.

 a one page request or


 visit to a website or
 store information about that user

19 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-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 −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the
implicit session object. Since session object is already provided to the JSP programmer, the
programmer can immediately begin storing and retrieving data from the object without any
initialization or getSession().
Here is a summary of important methods available through the session object −

S.No. Method & Description

public Object getAttribute(String name)


1
This method returns the object bound with the specified name in this session, or null if
no object is bound under the name.

public Enumeration getAttributeNames()


2
This method returns an Enumeration of String objects containing the names of all the
objects bound to this session.

public long getCreationTime()


3
This method returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.

public String getId()


4
This method returns a string containing the unique identifier assigned to this session.

public long getLastAccessedTime()


5
This method returns the last time the client sent a request associated with the this
session, as the number of milliseconds since midnight January 1, 1970 GMT.

public int getMaxInactiveInterval()


6
This method returns the maximum time interval, in seconds, that the servlet container
will keep this session open between client accesses.

public void invalidate()


7
This method invalidates this session and unbinds any objects bound to it.

20 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

public boolean isNew()


8
This method returns true if the client does not yet know about the session or if the client
chooses not to join the session.

public void removeAttribute(String name)


9
This method removes the object bound with the specified name from this session.

public void setAttribute(String name, Object value)


10
This method binds an object to this session, using the name specified.

public void setMaxInactiveInterval(int interval)


11
This method specifies the time, in seconds, between client requests before the servlet
container will invalidate this session.

Session Tracking Example


This example describes how to use the HttpSession object to find out the creation time and
the last-accessed time for a session. We would associate a new session with the request if one
does not already exist.

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


<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());

// Get last access time of this Webpage.


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


if (session.isNew() ){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);

21 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

session.setAttribute(visitCountKey, visitCount);
%>

<html>
<head>
<title>Session Tracking</title>
</head>

<body>
<center>
<h1>Session Tracking</h1>
</center>

<table border = "1" align = "center">


<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>

</body>
</html>
Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once
you run the URL, you will receive the following result −

Welcome to my website
Session Information

Session info Value

22 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

Id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 0

Now try to run the same JSP for the second time, you will receive the following result.

Welcome Back to my website


Session Information

info type Value

Id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 1

Deleting Session Data


When you are done with a user's session data, you have several options −
 Remove a particular attribute − You can call the public void
removeAttribute(String name) method to delete the value associated with the a
particular key.
 Delete the whole session − You can call the public void invalidate() method to discard
an entire session.
 Setting Session timeout − You can call the public void setMaxInactiveInterval(int
interval) method to set the timeout for a session individually.

23 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

 Log the user out − The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
 web.xml Configuration − If you are using Tomcat, apart from the above mentioned
methods, you can configure the session time out in web.xml file as follows.

<session-config>
<session-timeout>15</session-timeout>
</session-config>

The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session
in seconds. So if your session is configured in web.xml for 15
minutes, getMaxInactiveInterval( ) returns 900.

Connecting to database in JSP


The database is used for storing various types of data which are huge and has
storing capacity in gigabytes. JSP can connect with such databases to create and
manage the records.
To start with basic concept, let us create a table and create a few records in that table as follows

Create Table
To create the Employees table in the EMP database, use the following steps −

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>

24 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

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>

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>

SELECT Operation
Following example shows how we can execute the SQL SELECT statement using JTSL in
JSP programming −
<%@ 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"%>

25 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

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

Access the above JSP, the following result will be displayed −

Emp ID First Name Last Name Age

100 Zara Ali 18

26 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

101 Mahnaz Fatma 25

102 Zaid Khan 30

103 Sumit Mittal 28

INSERT Operation
Following example shows how we can execute the SQL INSERT statement using JTSL in
JSP programming −
<%@ 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>JINSERT Operation</title>
</head>

<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>
<sql:update dataSource = "${snapshot}" var = "result">
INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
</sql:update>

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

27 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4

<td><c:out value = "${row.age}"/></td>


</tr>
</c:forEach>
</table>

</body>
</html>
Access the above JSP, the following result will be displayed −

Emp ID First Name Last Name Age

100 Zara Ali 18

101 Mahnaz Fatma 25

102 Zaid Khan 30

103 Sumit Mittal 28

104 Nuha Ali 2

28 | P a g e
Dept of CSE R.Satheesh, Asst.Prof

You might also like