Professional Documents
Culture Documents
JSP
2.1 Overview:
JSP stands for “Java server page” and built by SUN Microsystem.
JSP technology is used to create web application. It focuses more on presentation logic of the
web application. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of
Servlets. Servlet adds HTML code inside Java code while JSP adds Java code inside HTML.
Everything a Servlet can do, a JSP page can also do it.
JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP
separates presentation and business logic as Web designer can design and update JSP pages
without learning the Java language and Java Developer can also write code without concerning
the web design.
JSP Architecture:
The web server needs a JSP engine ie., container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. 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.
The following steps explain how the web server creates the web page using JSP:
i. User requesting a JSP page through internet via web browser.
ii. The JSP request is sent to the Web Server.
iii. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet
Engine.
iv. If the JSP file has been called
» the first time then the JSP file is parsed
» otherwise servlet is instantiated.
v. The next step is to generate a servlet from the JSP file.
[In that servlet, all the HTML code is converted in println statements.]
vi. Now, the servlet source code file is compiled into a class file (bytecode file).
vii. The servlet is instantiated by calling the init and service methods of the servlet’s life
cycle.
v. Now, the generated servlet output is sent via the Internet form web server to user's
web browser.
vi. Now in last step, HTML results are displayed on the user's web browser.
In the end, a JSP is just a Servlet.
Life Cycle:
A JSP life cycle can be defined as the entire process from its creation till the destruction which is
similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet. The following are the paths
followed by a JSP
Compilation
Initialization
Execution
Cleanup
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 which is identical in both Java
Servlet and applet. It is called first when the JSP is requested and is used to initialize objects and
variables that are used throughout the life of the JSP.
Syntax: public void jspInit(){
//Initialization code...
}
JSP execution:
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method is automatically and retrieves a connection to HTTP. It will
call doGet or doPost() method of servlet created.
Syntax:
void _jspService(HttpServletRequest request,
HttpServletResponse response) {
// Service handling code... }
JSP cleanup:
The jspDestroy() method is automatically called when the JSP terminates normally. Override
jspDestroy() for cleanup where resources used during the execution of the JSP, such as such as
releasing database connections or closing open files.
Syntax: public void jspDestroy{
// Initialization code...
}
All the above mentioned steps can be shown below in the following diagram:
Extension to Servlet:
JSP technology is the extension to servlet technology. We can use all the features of
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.
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.
Example 1:
Comments.jsp
<%--
Document : SimpleJsp
Created on : Mar 2, 2015, 5:09:35 AM
Author : Suma
--%>
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%-- This comment will not be visible in the page source --%>
<p><b> Creating Template text: </b>
<\% out.println("Hello World"); \%><br>
</p>
</body>
</html>
Types of JSP Scripting Elements [invoking java code with JSP Scripting element]:
JSP scripting elements let you insert Java code into the servlet that will be generated from the
JSP page. There are three forms:
a. Declaration Tag
b. Scriptlet Tag
c. Expression Tag (For Definition refer table 2.1)
Example 2:
<html>
<head>
<title>Demo</title>
</head>
<%! int a=2, b=3; %>
<%! int sum(int x, int y){
return(x+y);
}
%>
<body>
<h1>Demo for Declaration tag</h1>
Addition of two values: <%= a+b %><br>
Addition of two values using function: <%= sum(10,20) %>
</body>
</html>
Control-Flow Statements:
JSP provides full power of Java to be embedded in your web application. You can use all
the APIs and building blocks of Java in your JSP programming including decision making
statements, loops etc.
Conditional Statements are:
Branching Statements: if, if-else, nested else-if, else-if Ladder, switch
Looping Statements: while, do-while, for, foreach
Jumping Statements: continue, break
Value.html
<html>
<head>
<title>Demo on Conditional Statements</title>
</head>
<body>
<form action="CondDemo.jsp" method="get">
Enter the Value:<input type="text" name="Evalue"/>
<input type="submit" name="Click Here"/>
</form>
</body>
</html>
<%@page="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Check Value using Conditions</title>
</head>
<body>
<%
String str=request.getParameter("Evalue");
if(str.equals(""))
out.println("String is Empty");
else {
int i= Integer.parseInt(str);
if(i==10)
out.println("Entered Value is Equal");
else
out.println("Entered Value is not equal");
}
%>
</body>
</html>
CondDemo.jsp [Scriptlet is closed at each line with HTML text included between
Scriptlet tags]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Check Value using Conditions</title>
</head>
<body>
<%
String str=request.getParameter("Evalue");
if(str.equals("")) { %>
<h2>String is Empty</h2>
<% } else {
int i= Integer.parseInt(str);
if(i==10) { %>
<h3>Entered Value is Equal</h3>
<% } else { %>
<h3>Entered Value is not equal</h3>
<% } %>
</body>
</html>
Output:
Now look at the following switch...case block which has been written a bit differently using
out.println() and inside Scriptlet as:
Example 4:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Check Value using Conditions</title>
</head>
<body>
<%
String str=request.getParameter("Evalue");
int i;
switch(i=(Integer.parseInt(str)==10)?1:0)
{
case 0: out.println("Entered Value is not Equal");
break;
case 1: out.println("Entered Value is Equal");
break;
default: out.println("Entered Proper Input");
}
%>
</body>
</html>
Looping Statements:
You can also use three basic types of looping blocks in Java: for, while, and do…while blocks
in your JSP programming.
Example 5:
Value.html
<html>
<head>
<title>Demo on Conditional Statements</title>
</head>
<body>
<form action="LoopDemo.jsp" method="get">
Enter the Value:<input type="text"
name="Evalue"/>
<input type="submit" name="Click Here"/>
</form>
</body>
</html>
LoopDemo.jsp
Output:
foreach Statement:
The for-each loop is mainly used to traverse array or collection elements. The advantage of
for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
Syntax:
for(data_type variable : array | collection){}
Example 6:
foreach.html
<html>
<head>
<title>foreachDemo</title>
</head>
<body>
<h1>Select knowing Laguages</h1>
<form action="LoopDemo.jsp" method="get">
<input type="checkbox" name="lang" value="C/C++" />
C/C++<br>
<input type="checkbox" name="lang" value="Java/J2EE" />
JAVA/J2EE<br>
<input type="checkbox" name="lang" value="JQuery" />
JQuery<br>
<input type="checkbox" name="lang" value="Python" />
Python<br>
<input type="submit" value="submit" name="clickhere" />
<br>
</form>
</body>
</html>
By Rama Satish K V, Dept. of MCA 1 | 46
Chapter 2 JSP
LoopDemo.jsp (Continued)
Output:
Jumping Statements:
You can also use jumping statements are break, continue in the JSP Programming.
Example 7:
index.html
<html>
<head>
<title>Demo on Looping Statements</title>
</head>
<body>
<form action="LoopDemo.jsp" method="get">
Enter the Value:<input type="text" name="Evalue"/>
<input type="submit" value="Click Here"/>
</form>
</body>
</html>
LoopDemo.jsp
There are a number of different ways to generate dynamic content from JSP, as illustrated in the
below figure.
Compilation: To compile a regular Java class, you press the Build button in your IDE or
invoke javac. To compile a JSP page, you have to drop it in the right directory, start the
server, open a browser, and enter the appropriate URL.
Debugging: We know this never happens to you, but when we write Java classes or JSP
pages, we occasionally make syntax errors. If there is a syntax error in a regular class
definition, the compiler tells you right away and it also tells you what line of code
contains the error. If there is a syntax error in a JSP page, the server typically tells you
what line of the servlet (i.e., the servlet into which the JSP page was translated) contains
the error. For tracing output at runtime, with regular classes you can use simple
System.out.println statements if your IDE provides nothing better.
Division of labor: Many large development teams are composed of some people who are
experts in the Java language and others who are experts in HTML but know little or no
Java. The more Java code that is directly in the page, the harder it is for the Web
developers (the HTML experts) to manipulate it.
Testing: Suppose you want to make a JSP page that outputs random integers between
designated 1 and some bound (inclusive). You use Math.random, multiply by the range,
cast the result to an int, and add 1.
If you do this directly in the JSP page, you have to invoke the page over and over to see if
you get all the numbers in the designated range but no numbers outside the range. After
hitting the Reload button a few dozen times, you will get tired of testing. But, if you do
this in a static method in a regular Java class, you can write a test routine that invokes the
method inside a loop and then you can run hundreds or thousands of test cases with no
trouble. For more complicated methods, you can save the output, and, whenever you
modify the method, compare the new output to the previously stored results.
Example:
Reuse: You put some code in a JSP page. Later, you discover that you need to do the
same thing in a different JSP page. What do you do? Cut and paste? Boo! Repeating code
in this manner is a cardinal sin because if you change your approach, you have to change
many different pieces of code. Solving the code reuse problem is what object-oriented
programming is all about. Don’t forget all your good OOP principles just because you are
using JSP to simplify the generation of HTML.
cssStyle.css
body {
background-color: #ffdd88;
font-family: CurlZ MT, tahoma, helvetica, arial,;
font-size: 1.9em;
}
ScriptletPage.jsp
</body>
</html>
DisplayUtilities.java
package Corepack;
In the above example, the goal is to generate a message of n times using scripting elements and
compare how the statements are translated into the servlet from the JSP page as shown below.
Since the structure of this page is fixed and we use a separate helper class for the display
method.
JSP declarations result in code that is placed inside the servlet class definition but
outside the _jspService method. Since fields and methods can be declared in any order,
it does not matter whether the code from declarations goes at the top or bottom of the
servlet.
JSP Expression result in code that we oversimplified the out variable (which is a
JspWriter, not the slightly simpler PrintWriter that results from a call to getWriter).
» JSP expressions basically become print (or write) statements in the servlet that
results from the JSP page.
» Whereas regular HTML becomes print statements with double quotes around
the text, JSP expressions become print statements with no double quote.
JSP Scriptlets can perform a number of tasks that cannot be accomplished with
expressions alone. These tasks include setting response headers and status codes,
invoking side effects such as writing to the server log or updating a database, or
executing code that contains loops, conditionals, or other complex constructs.
It is easy to understand how JSP scriptlets correspond to servlet code: the Scriptlet code
is just directly inserted into the _jspService method: no strings, no print statements, no
changes whatsoever.
..... }
Note: JSP expressions contain Java values and JSP scriptlets contain Java statements.
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:
Note:
Directives can have a number of attributes which you can list down as key-value pairs
and separated by commas.
The blanks between the @ symbol and the directive name, and between the last attribute
and the closing %>, are optional.
To obtain quotation marks within an attribute value, precede them with a backslash, using \’ for ’
and \" for ".
i. <%@ page . . . %> Let’s you control the structure of the servlet by importing classes,
customizing the servlet superclass, setting the content type, and
the like.
ii. <%@ include . . . %> Let’s you insert a file into the JSP page at the time the JSP file is
translated into a servlet.
The page directive is used to provide instructions to the container that pertain to the current
JSP page.
The page directive can define one or more of the following attributes and all are case-sensitive:
Sl.
Attributes Description
No.
i. import is used to define a set of class, interface or all the members of a package
that must be imported in servlet class definition
Syntax:
ii. contentType Defines the MIME (Multipurpose Internet Mail Extension) type of the
HTTP response.
Syntax:
iv. session Specifies whether or not the JSP page participates in HTTP sessions
Syntax:
v. isELIgnored Specifies whether the JSP Expression Language (EL) is ignored (true)
or evaluated normally (false).
Syntax:
<%@ page isELIgnored = “true" %>
vi. buffer specifies the buffer size in kilobytes used by the out variable, which is
of type JspWriter.
Syntax:
<%@ page buffer = “size kb" %>
Note:
Default size is 8Kb
Servers can use a larger buffer than you specify, but not a
smaller one.
For example: Refer Example-e
vii. autoFlush specifies whether the output buffer should be automatically flushed
when it is full (the default) or whether an exception should be raised
when the buffer overflows ( autoFlush="false").
Syntax:
viii. info defines a string that can be retrieved from the servlet by means of the
getServletInfo method.
Syntax:
ix. errorPage is used to define the error page, if exception occurs in the current page,
it will be redirected to the another JSP Page by the runtime.
Syntax:
x. iserrorPage indicates whether or not the current page can act as the error page for
another JSP page.
Syntax:
xi. isThreadSafe Servlet and JSP both are multithreaded. You can control that using
“isThreadSafe” atttribute.
Syntax:
If you make it false, the web container will serialize the multiple
requests, i.e. it will wait until the JSP finishes responding to a request
before passing another request to it.
xii. language The “language’ attribute is intended to specify the scripting language
being used.
Syntax:
xiii. extends It specifies the superclass of the servlet that will be generated for the
JSP page.
Syntax:
Output:
Example-b:
Welcome.java
package JavaPack;
Contentandpage.jsp [continued]
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>
Output:
Example-c:
sessionAtt.jsp
<%@page import="java.util.Date,JavaPack.*"
contentType="text/html" pageEncoding="Shift-JIS"
session= "true"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>
Output:
Example-d:
ReadEL.html
<html>
<head>
<title>Expression Language</title>
</head>
<body>
<form action="ExprLang.jsp">
Enter name: <input type="text" name="uname" /> <br><br>
<input type="submit" value="click here" />
</form>
</body>
</html>
ExprLang.jsp
Output:
Example-e:
buffAflush.jsp
<%@page import="java.util.Date,JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
session= "true"
buffer="16kb"
autoFlush="true"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>
Example-f:
infoAtt.jsp
<%@page import="java.util.Date,JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
info="Composed by Sonu Nigam"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css"
type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>
Output:
Example-g:
ErrorDemo.jsp
SendError.jsp
Example-h:
threadDemo.jsp
<%@page import="java.util.Date,JavaPack.*"
contentType="text/html" pageEncoding=" UTF-8"
isThreadSafe="false"%>
<!DOCTYPE html>
<!html>
<head>
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>
Output:
Example-i:
<%@page import="java.util.Date,JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
language="java"
extends="org.apache.jasper.runtime.HttpJspBase"
%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>
If you are writing XML-compatible JSP pages follow the below syntax:
The include directive tells the Web Container to copy everything in the included file and
paste it into current JSP file.
Welcome.jsp
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<%@ include file="header.jsp" %>
Welcome, User
</body>
</html>
Header.jsp
Output:
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.
All the above action tag have to write using syntax as mentioned below:
Syntax:
<jsp:ActionTags Attribute= “names” >
</jsp:ActionTags>
It is used to forward the request to another resource it may be jsp, html or another
resource.
Syntax:
Without Parameter
<jsp:forward page= “RelativeURL / <%= ExpressionTag %>” >
<!- - Write zero or more param tags- - >
</jsp:forward>
With Parameter
<jsp:forward page= “RelativeURL / <%= ExpressionTag %>” >
<jsp:param name=“paramname” value=“parmavalue”/>
</jsp:forward>
Example:
forwardDemo.jsp
printDate.jsp
Output:
With Parameter
Example:
includeDemo.jsp
printDate.jsp
Output:
include Directive
jsp:include
<%@include ----- %>
includes resource at translation time. includes resource at request time.
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response,
"printDate.jsp" + "?" +
rg.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("user",
request.getCharacterEncoding())+ "=" +
org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("suma",
request.getCharacterEncoding()), out, false);
It is used to embed applet or bean in the jsp file. The jsp:plugin action tag downloads
plugin at client side to execute an applet or bean.
Syntax:
<jsp:plugin> tags generates the element <OBJECT> or <EMBED> tags during the action time.
Example:
pluginDemo.jsp
JspPluginApplet.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
Output:
This element which is used by the client browser in case the plugin cannot be started, that do
not support for OBJECT or EMBED. This action cannot be used elsewhere outside the
<jsp:plugin> action.
Syntax:
A jsp:param entries must be enclosed within a “jsp:params” element. This action cannot
be used elsewhere outside the <jsp:plugin> action.
Syntax:
<jsp:plugin page= “RelativeURL / <%= ExpressionTag %>” >
<jsp:params>
<jsp:param name=“paramname1” value=“parmavalue1”>
<jsp:param name=“paramname2” value=“parmavalue2”>
</jsp:params>
</jsp:plugin>
Example:
pluginDemo.jsp
JspPluginApplet.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
import javax.swing.JLabel;
Output:
Beans are simply Java classes that are written in a standard format( javaBeans API).
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 implement the java.io.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.
● Class must not define any public instance variables.
Advantages:
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.
No Java Syntax
Example:
<jsp:useBean id=“person” class=“PersonBean” scope=“request”/>
jsp:getProperty This element reads and outputs the value of a bean property.
Syntax:
Example:
<jsp:getProperty name=“person” property=“name”/>
jsp:setProperty This element modifies a bean property.
Syntax:
Example:
<jsp:setProperty name=“person” property=“name”/>
The setProperty tag is used to store data in JavaBeans instances. The syntax of setProperty
tag is
<jsp:setProperty name="beanName" property="*" >
or
<jsp:setProperty name="beanName" property="propertyName">
or
<jsp:setProperty name="beanName“ property="propertyName"
param="parameterName" >
or
<jsp:setProperty name="beanName" property="propertyName"
value="propertyValue" >
Example:
useBeanDemo.jsp
useBeanDemo.jsp [continued]
package bean;
import java.io.Serializable;
//Default Constructor
public PersonBean(){
this.name="RNSIT";
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Output:
Output:
<!html>
<head>
<title>Attributes demo</title>
<link rel=stylesheet href="stylesheet.css" type="text/css">
</head>
<body>
<h2>List of Names and Address</h2>
<% String str=request.getParameter("format");
if(!str.isEmpty()&& str.equals("excel"))
response.setContentType("application/vnd.ms-excel");
%>
<TABLE BORDER=1>
<TR><TH>First</TH><TH>Last</TH><TH>Email Address</TH></TR>
<TR><TD>Marty</TD><TD>Hall</TD><TD>hall@corewebprogramming.com
</TD></TR>
<TR><TD>Larry</TD><TD>Brown</TD><TD>brown@corewebprogramming.com
</TD></TR>
<TR><TD>Bill</TD><TD>Gates</TD><TD>gates@sun.com</TD></TR>
<TR><TD>Larry</TD><TD>Ellison</TD><TD>ellison@microsoft.com
</TD></TR>
</TABLE>
</body>
</html>
Output:
Implicit Objects:
Implicit
Description
Object
request The HttpServletRequest object associated with the request.
The HttpServletRequest object associated with the response that is sent
response
back to the browser.
out The JspWriter object associated with the output stream of the response.
The HttpSession object associated with the session for the given user of
session
request.
application The ServletContext object for the web application.
config The ServletConfig object associated with the servlet for current JSP page.