Unit 11 JSP
Unit 11 JSP
JSP
(Java Server Pages)
JSP Basics
• A typical JSP page very much looks like html page with all the html
markup except that you also see Java code in it. So, in essence,
HTML + Java = JSP
• Therefore, JSP content is a mixed content, with a mixture of HTML
and Java.
• If this is the case, let me ask you a quick question. Can we save this
mixed content in a file with “.html” extension?
• No we can’t, because the html formatter will also treat the Java
code as plain text which is not what we want.
• We want the Java code to be executed and display the dynamic
content in the page. For this to happen, we need to use a different
extension which is the “.jsp” extension.
• Good. To summarize, a html file will only have html markup, and a
jsp file will have both html markup and Java code. Point to be
noted.
Fig: HTML and JSP page request
• The above picture should give you some idea of how a web container
processes html requests and JSP requests.
• When the browser requests for html file, the web container simply
responds with a html response without any processing.
• However, when the browser sends a JSP page request, the web
container assumes that the JSP page might include Java code, and
translates the page into a Servlet.
• The servlet then processes the Java code, and returns the complete html
response including the dynamic content generated by the Java code.
• Though the web container does the translation of JSP to Servlet, we
need to know how it does this translation.
• For a web container to translate JSP, it needs to identify from the JSP
page, as to which is HTML markup and which is Java code.
• According to J2EE specification, a JSP page must use special symbols as
placeholders for Java code.
• The web container instead of scratching its head to identify Java code,
simply uses the special symbols to identify it. This is a contract between
JSP and the Web container. This is an example of making life easy.
• In JSP, we use four different types of placeholders for Java
code. Following table shows these placeholders along with
how the web container translates the Java code with them.
<HTML>
<BODY>
<h4> This is the response from the current JSP page</h4>
<h3> Following is the response from another JSP </h3>
<hr/>
<%@ include file=”/jsps/PageDirectiveDemo.jsp” %>
<hr/>
</BODY>
</HTML>
The taglib directive
• This directive allows the JSP page to use custom tags written in
Java.
• Custom tag definitions are usually defined in a separate file
called as Tag Library Descriptor.
• For the current JSP to use a custom tag, it needs to import the
tag library file which is why this directive is used. Following is
how taglib directive is used.
• <%@ taglib uri=”location of definition file” prefix=”prefix
name” %>
• Custom tags and tag libraries are explained in detail in the later
pages and we’ll see how to use this directive at that point. For
now, don’t worry about it.
• Now that we know how and when to use JSP directives, let’s
see the usage of another type of placeholder.
JSP Declarations
• JSP declarations are used to declare global variables and
methods that can be used in the entire JSP page. A
declaration block is enclosed within <%! and %> symbols as
shown below:
<%!
Variable declarations
Global methods
%>
JSPDeclarationDemo.jsp
<%@ page import = "java.util.Date" %>
<%!
String getGreeting( String name){
Date d = new Date();
return "Hello " + name + "! It's "+ d + " and how are you doing
today";
}
%>
<h3> This is a JSP Declaration demo. The JSP invokes the global method
to produce the following
</h3>
<hr/>
<h3> <%= getGreeting("James Bond") %>
<hr/>
JSP Expressions
• Expressions in JSP are used to display the dynamic content in
the page.
• An expression could be a variable or a method that returns
some data or anything that returns a value back. Expressions
are enclosed in <%= and %> as shown below
• <%= Java Expression %>
<%!
String name="John Smith";
String address = "1111 S St, Lincoln, NE, USA";
String getMessage(){
return "Your shipment has been sent to the following address.
Thank you for shopping at BuyForLess.com";
}
%>
<h3> Your order is successfully processed. The confirmation number is
876876
</h3>
<hr/>
<h3> <%= getMessage() %> </h3>
<h4> <%= name %>
<%= address %>
</h4>
<hr/>
JSP Scriptlets
• A Scriptlet is a piece of Java code that represents processing logic to
generate and display the dynamic content where ever needed in
the page. Scriptlets are enclosed between <% and %> symbols. This
is the most commonly used placeholder for Java code
<HTML>
<HEAD>
<TITLE>Tag - Methods</TITLE>
</HEAD>
<h3> This is an example using Scriplets </h3>
<%
int sum=0;
for(int i=1;i<=100;i++) {
sum+=i;
}
%>
<hr/>
The sum of first 100 numbers is <%= sum %>
<hr/>
<h3> Following is generated by the Loop
<%
for(int i=2;i<=5;i++){
if( i % 2 == 0){
%>
<br/><%=i %> is an even number
<% }
else{
%>
<br/><%= i %> is an odd number
<%
}
} // End of for loop
%>
</HTML>
Implicit Objects
• As the name suggests every JSP page has some implicit
objects that it can use without even declaring them.
• The JSP page can readily use them for several purposes.
• Following table lists the implicit objects.
Implicit Object Description
request This is an object of HttpServletRequest class. Used for
reading request parameters (Widely used)
response This is an object of HttpServletResponse class. Used for
displaying the response content. This is almost never used
by the JSP pages. So, don’t worry about it.
session This is an object of HttpSession class used for session
management. (Widely Used)
application This is an object of ServletContext. Used to share data by all
Web applications. Rarely used.
out This is an object of JspWriter. Similar to PrintWriter in
Servlet. Rarely used.
• Out of all the above implicit objects, only request and session
objects are widely used in JSP pages.
• The request object is used for reading form data and session
object is used for storing and retrieving data from session.
• Let’s see an example using request and session implicit
objects.
• In this example, we will have html form post some data to a
JSP page with reads the form parameters and stores them in
the session.
• We will then write another JSP that reads the data from the
session and displays them in the browser.
Login.jsp
<html>
<body>
<form action="StoreData.jsp">
<table border=1>
<tr> <td> Login Name </td>
<td> <input type="text" name="username" size="20"/></td>
</tr>
<tr> <td> Password </td>
<td> <input type="password" name="password" size="20"/></td>
</tr>
<tr> <td> <input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</html>
StoreData.jsp
<%@ page session="true" %>
<%
// Read the data from the request
String name = request.getParameter("username");
String pwd = request.getParameter("password");
// Store the data in the session
session.setAttribute("userid",name);
session.setAttribute("password",pwd);
%>
<h3> This page read the form data and stored it in the session.</h3>
<a href="RetrieveData.jsp">Click Here</a> to go to the page that
displays the data.
RetrieveData.jsp
<%@ page session="true" %>
<%
// Read the data in the session
String name = (String)session.getAttribute( "userid");
String pwd = (String)session.getAttribute("password");
%>
<h3>
The username is <%= name %> <br/>
The password is <%= pwd %>
• The StoreData.jsp does two things listed below:
• 1. Read the form data using the request implicit object.
String name = request.getParameter("username");
String pwd = request.getParameter("password");
• 2. Store the form data in the session using the session implicit
object.
session.setAttribute( "userid",name);
session.setAttribute("password",pwd);
• This page then provides a link to the RetriveDa
• The RetrivePage.jsp reads the data stored in the session as shown
below and displays it.
String name = (String)session.getAttribute( "userid");
String pwd = (String)session.getAttribute("password");
Java Bean
A Java Bean is a java class that should follow following
conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the
properties, known as getter and setter methods.
Why use Java Bean?
• It is a reusable software component.
• A bean encapsulates many objects into one object, so we can
access this object from multiple places.
• Moreover, it provides the easy maintenance.
Employee.java
package beans;
public class Employee {
private int id;
private String name;
public int getId() {
return id;}
public void setId(int id) {
this.id = id;}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Test.java
package beans;
public class Test {
public static void main(String[] args) {
Employee e=new Employee();
e.setId(1);
System.out.println(e.getId());
e.setName("James Bond");
System.out.println(e.getName());
}
}
Java Beans in JSP
• One of the good practices while writing JSP is to isolate the
presentation logic (HTML) from business logic (Java code).
• A typical JSP page should have as minimum business logic as
possibly can. If this is the case, where should the business logic
be?
• The business logic will be moved into external entities which
will then be accessed from within JSP page. These external
entities are nothing but Java beans.
• A Java bean is a simple class with getters and setters.
• Using Java beans in JSP offers whole lot of flexibility and avoids
duplicate business logic.
• JSP technology uses standard actions for working with beans.
So, let’s see how we can use beans in JSP and simplify our life.
• 1. <jsp:useBean>
• 2. <jsp:setProperty>
• 3. <jsp:getProperty>
jsp:useBean
• This action is used by the web container to instantiate a Java Bean
or locate an existing bean.
• The web container then assigns the bean to an id which the JSP can
use to work with it.
• The Java Bean is usually stored or retrieved in and from the
specified scope.
• The syntax for this action is shown below:
• <jsp:useBean id=”bean name” class=”class name” scope=”scope
name”/>
where,
• id - A unique identifier that references the instance of the bean
• class - Fully qualified name of the bean class
• scope – The attribute that defines where the bean will be stored or
retrieved from; can be request or session (widely used)
• Consider the following declaration.
• <jsp:useBean id = “cus” class=”beans.Customer” scope=”session” />
• With the above declaration, following is what the web container
does.
1. Tries to locate the bean with the name cus in session scope. If
it finds one, it returns the bean to the JSP.
2. If the bean is not found, then the container instantiates a new
bean, stores it in the session and returns it to the JSP.
• If the scope is session, then the bean will be available to all the
requests made by the client in the same session.
• If the scope is request, then the bean will only be available for the
current request only.
jsp:setProperty
• This action as the name suggests is used to populate the bean
properties in the specified scope. Following is the syntax for this
action.
• <jsp:setProperty name ="bean name" property ="property name"
value= "data" />
• For instance, if we need to populate a bean whose property is
firstName with a value John we use this action as shown below:
• <jsp:setProperty name "cus" property ="firstName" value= "John"
/>
jsp:getProperty
• This standard action is used to retrieve a specified property from a
bean in a specified scope. Following is how we can use this action to
retrieve the value of firstName property in a bean identified by cus in
the session scope.
• <jsp:getProperty name=”cus” property=”firstName” scope=”session” />
• There are two common scenarios with using JavaBeans in JSP.
• Scenario 1: JSP collects the data from the client, populate the bean's
properties and stores the bean in request or session scope. This bean
will then be used by another server side component to process the
data.
• Scenario 2: A Server side component loads a Java Bean with all the
information and stores it in the request or session. The JSP will then
retrieve the bean and displays the information to the client.
• In scenario 1, JSP uses the bean to collect the data into it, while in
scenario 2, it uses the bean to read the data from it to display.
• The following example demonstrates scenario 1 in which a html
form posts the data to a JSP page. The JSP page will then collect the
data and store it in a Java Bean named Customer in session scope.
• It then provides a link to a servlet which retrieves the bean from the
session and process the data in it.
Calculator.java
package beans;
public class Calculator {
public int cube(int m){
return m*m*m;
}
}
Calc.jsp
<jsp:useBean id="cal" class="beans.Calculator"/>
<%
int m = cal.cube(5);
out.print("cube of 5 is" + m);
%>
CustomerForm.html
<html>
<head> <title> Customer Form </title> </head>
<body>
<h3>Please fill in the following details and submit it </h3> <br/>
<form action="CustomerInfoGatherer.jsp" method="GET">
First Name: <input type="text" name="firstName" > <br>
Middle Name: <input type="text" name="middleName"> <br>
Last Name: <input type="text" name="lastName"> <br>
Age: <input type="text" name="age" > <br>
SSN: <input type="text" name="ssn"> <br>
City: <input type="text" name="city"> <br>
State: <input type="text" name="state"> <br>
Country: <input type="text" name="country"> <br>
<input type="submit" name="Submit"/>
</form>
</body>
</html>
Customer.java
package beans;
public class Customer implements java.io.Serializable {
String firstName;
String middleName;
String lastName;
String age;
String ssn;
String city;
String state;
String country;
public String getAge() {
return age;}
public void setAge(String age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;}
public void setCountry(String country) {
this.country = country;
}
public String getFirstName() {
return firstName;}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getSsn() {
return ssn;
}