0% found this document useful (0 votes)
28 views

WT - Unit - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

WT - Unit - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Web Technologies Unit - V

Java Server Pages (JSP)


JSP - Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is responsible
for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container
to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment and other services a JSP
needs. It knows how to understand the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

 As with a normal page, your browser sends an HTTP request to the web server.

 The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.
This is done by using the URL or JSP page which ends with .jsp instead of .html.

 The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and all
JSP elements are converted to Java code. This code implements the corresponding dynamic
behavior of the page.

 The JSP engine compiles the servlet into an executable class and forwards the original request to
a servlet engine.

 A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format. The output is furthur passed on to
the web server by the servlet engine inside an HTTP response.

 The web server forwards the HTTP response to your browser in terms of static HTML content.

 Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.

Department of IT, VJIT Page 1


Web Technologies Unit - V

All the above mentioned steps can be seen in the following diagram –

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the
modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the
JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's
contents. This makes the process more efficient than with the other scripting languages (such as PHP)
and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet.

JSP - Lifecycle
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.
Paths Followed By JSP
The following are the paths followed by a JSP −
 Compilation
 Initialization
 Execution
 Cleanup
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases have
been described below −

Department of IT, VJIT Page 2


Web Technologies Unit - V

JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If
the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP
engine compiles the page.
The compilation process involves three steps −
 Parsing the JSP.
 Turning the JSP into a servlet.
 Compiling the servlet.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to
perform JSP-specific initialization, override the jspInit() method −
public void jspInit()
{
// Initialization code...
}
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes
the _jspService() method in the JSP.

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.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy
when you need to perform any cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form −
public void jspDestroy()
{
// Your cleanup code goes here.
}

Department of IT, VJIT Page 3


Web Technologies Unit - V

Elements of JSP
The elements of JSP have been described below −
1. 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 %>

Note: Any text, HTML tags, or JSP elements you write must be outside the scriptlet.

Example
<html>
<head><title>Hello World</title></head>
<body>
Hello World! <br>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

2. 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 for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>

Example

<%! int i = 0; %>


<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

3. 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.
 Because the value of an expression is converted to a String, you can use an expression within a line of
text, whether or not it is tagged with HTML, in a JSP file.
 The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.
Syntax of JSP Expression −
<%= expression %>

Example
<html>
<head><title>A Comment Test</title></head>
<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>

Department of IT, VJIT Page 4


Web Technologies Unit - V

4. JSP Comments
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful
when you want to hide or "comment out", a part of your JSP page.

Syntax of the JSP comments −


<%-- This is JSP comment --%>

5. JSP Directives
A JSP directive affects the overall structure of the servlet class.

Syntax of the JSP Directives −


<%@ directive attribute="value" %>

There are three types of directive tag –


S.No. Directive & Description

<%@ page ... %>


1 Defines page-dependent attributes, such as scripting language, error page,
and buffering requirements.

<%@ include ... %>


2
Includes a file during the translation phase.

<%@ taglib ... %>


3
Declares a tag library, containing custom actions, used in the page

6. JSP Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.

Syntax for the Action element, as it conforms to the XML standard −


<jsp:action_name attribute="value" />

Action elements are basically predefined functions. Following table lists out the available JSP Actions –
S.No. Syntax & Purpose

jsp:include
1
Includes a file at the time the page is requested.

jsp:useBean
2
Finds or instantiates a JavaBean.

jsp:setProperty
3
Sets the property of a JavaBean.

jsp:getProperty
4
Inserts the property of a JavaBean into the output.

jsp:forward
5
Forwards the requester to a new page.

Department of IT, VJIT Page 5


Web Technologies Unit - V

jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin.

jsp:element
7
Defines XML elements dynamically.

jsp:attribute
8
Defines dynamically-defined XML element's attribute.

jsp:body
9
Defines dynamically-defined XML element's body.

jsp:text
10
Used to write template text in JSP pages and documents.

Anatomy of JSP

Department of IT, VJIT Page 6


Web Technologies Unit - V

JSP Implicit Objects


JSP supports nine automatically defined variables, which are also called implicit objects.
These variables are –

S.No. Object & Description

request
1
This is the HttpServletRequest object associated with the request.

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

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.

application
5
This is the ServletContext object associated with the application context.

config
6
This is the ServletConfig object associated with the page.

pageContext
7
This encapsulates use of server-specific features like higher performance JspWriters.

page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.

Exception
9
The Exception object allows the exception data to be accessed by designated JSP.

Department of IT, VJIT Page 7


Web Technologies Unit - V

Using Beans in JSP Pages


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 –

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.

Example: (StudentsBean.java)
package com;
public class StudentsBean implements java.io.Serializable
{
private String firstName = null;
private String lastName = null;

public StudentsBean()
{
}
//Get Methods
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}

//Set Methods
public void setFirstName(String firstName)
{
this.firstName = firstName;
}

Department of IT, VJIT Page 8


Web Technologies Unit - V

public void setLastName(String lastName)


{
this.lastName = lastName;
}
}

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" />
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.
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>

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.
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 getor the set methods that should be invoked.

Example (StudentsBean.jsp) shows how to access the data using the above syntax −
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ page import="com.StudentsBean"%>
<html>
<head>
<title>get and set properties Example</title>
</head>

<body>
<jsp:useBean id = "students" class = "com.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value =
"Eeswar"/>
<jsp:setProperty name = "students" property = "lastName" value =
"Banala"/>

Department of IT, VJIT Page 9


Web Technologies Unit - V

</jsp:useBean>

<p>Student First Name:


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

<p>Student Last Name:


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

</body>
</html>

Department of IT, VJIT Page 10


Web Technologies Unit - V

Session Tracking in JSP


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 void setAttribute(String name, Object value)


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

public Object getAttribute(String name)


2 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()


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

public long getCreationTime()


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

public String getId()


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

public long getLastAccessedTime()


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

public int getMaxInactiveInterval()


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

public void invalidate()


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

public boolean isNew()


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


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

Session Tracking Example


W11.a.jsp (Setting the Session variables)
<%@page language="java" import="java.util.*" import="java.text.*"
errorPage=""%>
<form method="get" action="w11b.jsp">
<%
SimpleDateFormat sd = new SimpleDateFormat("dd.MM.yyyy 'at' HH:mm:ss z");

Department of IT, VJIT Page 11


Web Technologies Unit - V

Date d=new Date();


sd.setTimeZone(TimeZone.getTimeZone("IST"));
%>
<p align="right"> Time:<%=sd.format(d)%></p>
<%
String un=request.getParameter("uname");
session.setAttribute("user",un);
session.setAttribute("time",d.getTime());
%>
Hello <%=un%>
<br><br>
<input type="submit" value="Logout">
</form>

W11b.jsp (Accessing the Session variables)


<%@page language="java" import="java.util.*" errorPage=""%>
<%
Date d2=new Date();
String un=(String)session.getAttribute("user");
Long t1=(Long)session.getAttribute("time");
Long t2=d2.getTime();
%>
Thank you <%=un%>
<br><br>
Session duration: <%=(t2-t1)/(60*60)%> seconds
<% session.invalidate();%>

W11.html
<html>
<head> <title> SESSION LOGIN </title> </head>
<body>
<center>
<form action="w11a.jsp" method="get">
Enter Name: <input type="text" name="uname"> <br><br>
<input type="submit" value="LOGIN" name="register">
</form>
</center>
</body>
</html>

Department of IT, VJIT Page 12


Web Technologies Unit - V

MVC Architecture in JSP


MVC stands for Model View and Controller. It is a design pattern that separates the business logic,
presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentation i.e. UI(User Interface).

Advantage of MVC (Model 2) Architecture


1. Navigation Control is centralized
2. Easy to maintain the large application

Department of IT, VJIT Page 13

You might also like