You are on page 1of 12

Java Server Pages: JSP

JavaServer Pages (JSP) is specification for combining Java with HTML to provide dynamic
content forWeb pages. When you create dynamic content, JSPs are more convenient to write
than HTTP servlets because they allow to embed Java code directly into HTML pages, in
contrast with HTTP servlets, in which you embed HTML inside Java code.

JSP is part of the Java 2 Enterprise Edition (J2EE). JSP enables to separate the dynamic content
of aWeb page from its presentation. It caters to two different types of developers: HTML
developers, who are responsible for the graphical design of the page, and Java developers, who
handle the development of software to create the dynamic content.

A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with
an additional step which is required to compile a JSP into servlet. The four phases have been described below

• void jspInit()
• Void jspService (HttpServletRequest request, HttpServletResponse response)
• public void jspDestroy()

Installation:
This involves downloading an implementation of the Java Software Development Kit (SDK) and
setting up the CLASS PATH environment variable is not required . The WEB-INF can be
avoided in JSP

JSP tags

Five types of Tags


1. Comments Tag <%-- This is JSP comment --%>

JSP comments start with <%-- and end with --%>, and are not included in the output Web page:
<%-- Some comments --%>
2. Declarations Tag <%! int a, b, c; %>

Declarations do not generate the output to the user’s screen. They are used for declaring class
variables and methods and start with <%! . The lastName variable declared in the following code
is only available in the current page:

<%! String lastName; %>


3. Directives Tag <%@ import="java.sql.* %>

Directives do not generate screen output. They inform the JSP engine about the rules to be
applied to the JSP. The page directive starts with <%@ page and will be applied during the
servlet-generation process only to the current page. It’s used with such attributes as import,
extends, session, errorPage, and contentType. For example, an equivalent of the Java import
statement looks like this:

<%@ page import=”java.io.*” %>

4. Expressions Tag <%= expression %>

JSP expressions start with <%= and can contain any Java expression, which will be evaluated
and its result inserted into the HTML page right where the expression is located.

5. Scriptlets Tag <% code fragment %>


Scriptlets can contain any valid Java code that will be included in the method jspService during
servlet-code generation. For example, within scriptlets you can also insert variable and method
declarations, Java expressions, and so on. Scriptlets start with <%. The jspService method is
responsible for generating the Web-page output, as in the following example:

<% lastName = “Smith”; %>

The JSP API


The JSP API contains the following packages:
javax.servlet.jsp package
1. The JspPage interface
2. The HttpJspPage interface

The JSP API consists of two packages:


1. javax.servlet.jsp
2. javax.servlet.jsp.tagext

JSP : Variables and Objects

JSP Varibale and objects are declared using declarative tags. It follows the java
variable standard and object creation methods. The following jsp program shows
how to declare the objects and variables in JSP
<html>
<head>
<title>JSP Example1</title>
</head>
<body>

<%! String myName="Arun Kumar"; %>


<%! int ID=12345; %>

<P>
<B>Your Name is : <%=myName%></B>
<B>Your ID is : <%=ID%></B>
</P>

</body>
</html>

Methods:
<html>
<head>
<meta charset="ISO-8859-1">
<title>First jsp pactice</title>
</head>
<body>

<%! int a=10; %>


<%! int b=10; %>
<%=a+b%>

<%! int addtwono(int a, int b)


{ return (a+b); }
%>

<%=addtwono(20,20)%>

</body>
</html>

Control Statements, Loops:


There are various standard programming languages like C, C++, Java etc. that supports control
statements. On the basis of that, JSP also follows the same methodology. Let’s study the flow of
control statements in Java Server Pages. Here, are some conditional statements about which we
will discuss:
 if else
 switch
 for loop
 while loop

IF…ELSE
JSP allows to use IF ELSE conditional statement as a programming logic of scriptlet tag. Apart
from that, IF can also be used in many other ways like nested IF or standalone IF. Here is a
simple example of IF ELSE statement.
<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<%! int num=8; %>
<% if(num%2==0)
{
out.println("Number is even");
}
else
{
out.println("Number is odd");
}
%>
</body>
</html>

Switch Statement
Switch is used to maintain the flow of control statement. It contains various cases with one
default case. The default case will execute only once, when none other case satisfies the
condition. Here, is a simple example of switch statement.
<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<%! int weekday=4; %>
<%
switch(weekday)
{
case 1:
out.print("Monday");
break;
case 2:
out.print("Tuesday");
break;
case 3:
out.print("Wednesday");
break;
case 4:
out.print("Thursday");
break;
case 5:
out.print("Friday");
break;
case 6:
out.print("Saturday");
break;
default:
out.print("Sunday");
break;
}
%>
</body>
</html>
For Loop
Here, is a simple example of for loop.
<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<%
for(int i=0;i<5;i++)
{
for(int j=1;j<=i+1;j++)
{
out.print(j);
}
out.print("<br>");
}
%>
</body>
</html>
While loop
Here, is a simple example of while loop.
<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<%
int i=0;
while(i<4)
{
i++;
out.print(i+"<br>");
}
%>
</body>
</html>

Request String : Parsing other information


The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request
by the web container. It can be used to get request information such as parameter, header
information, remote address, server name, server port, content type, character encoding etc. JSP
response is an implicit object of type HttpServletResponse. The instance of HttpServletResponse
is created by the web container for each jsp request. It can be used to add or manipulate response
such as redirect response to another resource, send error etc.

It can also be used to set, get and remove attributes from the jsp request scope. The following
example shows how request parameters are handled in jsp.
Index.html
<html>
<head>
<title>Request string example of JSP</title>
</head>
<body>
<form action="userinfo.jsp">
Enter User Name: <input type="text" name="uname" /> <br><br>
Enter Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Submit Details"/>
</form>
</body>
</html>
The following userinfo.jsp file will read the input given from html file

userinfo.jsp:
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
String username=request.getParameter("uname");
String password=request.getParameter("pass");
out.print("Name: "+username+" Password: "+password);
%>
</body>
</html>

Parsing other information:

In JSP the URL divided into 4 parts, which are


– Protocol (http/https/ etc)
– Host and port combination (localhost:8080)
• Host is IP( Internet protocol)
– Virtual path
– Physical path

Any URL contains these parts will be interpreted by the jsp program.

User Sessions

The JSP prorgram given in session objects is able to track session as the client moves between
HTML and JSP Program
Cookies

Cookie is a information created by JSP program and stored on the client hard disk by the
browser
Used to track a session with JSP database system In JSP cookie are the object of the class
javax.servlet.http.Cookie. This class is used to creates a cookie, a small amount of
information sent by a servlet to a Web browser, saved by the browser, and later sent back to
the server.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number. The getCookies() method of the
request object returns an array of Cookie objects. Cookies can be constructed using the
following code:
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

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>

// Reading JSP Cookies


<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with the this domain
cookies = request.getCookies();

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>

</html>

The cookies output will be displayed as per the given input from the html file

Setting Cookies
First Name: xxxx
Last Name: xxxx
// Reading JSP Cookies
Reading Cookies
Found Cookies Name and Value
Name : first_name, Value: xxxx
Name : last_name, Value: xxxx
Name : JSESSIONID, Value: F370491617976E93202A2865D48C1C82

Session Objects:
Several interactions between a browser and a server. Sessions provide such a mechanism. A
session can be created via the getSession( ) method of HttpServletRequest. An HttpSession
object is returned. This object can store a set of bindings that associate names with objects. The
setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of
HttpSession manage these bindings

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


<%
// 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("Surendra");

// Check if this is new comer on your web page.


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);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking Example</h1>
</center>
<table border="1" align="center">
<tr bgcolor="#ffcccc">
<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>

The program displays the output as follows:

Session Tracking Example


Session info Value

id C9FA02EE8236669840513C5E697656A5

Creation Time Tue May 04 22:49:44 IST 2021

Time of Last Access Tue May 04 22:49:44 IST 2021

User ID Surendra

Number of visits 1

You might also like