Module 2
JSP AND CONTROLLING THE STRUCTURE OF
GENERATED SERVLETS
Contents
Invoking java code with JSP scripting elements
Creating Template Text
Invoking java code from JSP
Limiting java code in JSP
Using jsp expressions
Comparing servlets and jsp
Writing scriptlets
For example Using Scriptlets to make parts of jsp conditional
Using declarations
Declaration example
JSP as Servlet
Invoking java code with JSP scripting
elements
JSP Scripting element are written inside <% %> tags.
These code inside <% %> tags are processed by the JSP engine during translation of the
JSP page.
Any other text in the JSP page is considered as HTML code or plain text.
Creating Template Text
JSP document consists of static text (usually HTML), known as template text.
There are two minor exceptions to the “template text is passed straight through” rule.
First, if you want to have <% or %> in the output, you need to put <\% or %\> in the output,
you need to put <\% or %\> in the template text.
Second, if you want a comment to appear in the JSP page but not in the resultant document, use
<%-- JSP COMMENTS --%>
HTML comments of the form are passed through to the client normally
<!-- HTML COMMENTS -->
Invoking java code from JSP
There are a number of different ways to generate dynamic content
from JSP, as illustrated in the below figure.
Types of JSP Scripting Elements
JSP scripting elements allows to insert Java code into the servlet that will be generated f
JSP page. There are three forms:
1. Expressions of the form, which are evaluated and inserted into the servlet’s output.
2. Scriptlets of the form, which are inserted into the servlet’s _jspService method (called
service).
3. Declarations of the form, which are inserted into the body of the servlet class, outside
existing methods.
4. Directive is used to provide instructions to the container.
Limiting java code in JSP
There are two options
Put 25 lines of Java code directly in the JSP page
Put those 25 lines in a separate Java class and put 1 line in the JSP page t
invokes it
Why is the second option much better?
Development- Write the separate class in a Java environment (editor or IDE), not an HTML
environment
Compilation. To compile a regular Java class, you press the Build button in your IDE or invoke
javac.
Debugging- If there are syntax errors, it is immediately seen at compile time.
Testing. You can write a test routine with a loop that does 10,000 tests and reapply it after each
change.
Reuse. You can use the same class from multiple pages
Using jsp expressions
A JSP expression is used to insert values directly into the output. It has the following form.
<%= Java Expression %>
The expression is evaluated, converted to a string, and inserted in the page.
This evaluation is performed at runtime (when the page is requested) and thus has full access to
information about the request.
For example, the following shows the date/time that the page was requested.
Current time: <%= new java.util.Date( ) %>
Predefined Variables
(or implicit objects)
To simplify these expressions, a number of predefined variables (or “implicit
objects”). are used.
These Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being
explicitly declared.
For example you can retrieve HTML form parameter data by
using request variable, which represent the HttpServletRequest object.
The “request” object is
implicit here, associated with
HttpServletRequest object
<%
String user = request.getParameter(“user”);
%>
The ”out” object is implicit in
JSP, associated with JspWriter
object
Hello, <% out.println(user); %>
Following are the JSP implicit object:
Implicit Object Description
request The HttpServletRequest object associated with the request.
response The HttpServletResponse object associated with the response
that is sent back to the browser
session The HttpSession object associated with the session for the
given user of request.
out The JspWriter object associated with the output stream of the
response.
application The ServletContext object for the web application.
exception The exception object represents the Throwable object that was thrown
by some other JSP page.
Jsp/Servlet Correspondence
Example: Sample JSP Expression: Random Number
<H1>A Random Number</H1>
<%= Math.random() %>
Resulting Servlet Code: Random Number
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("<H1>A Random Number</H1>");
out.println(Math.random());
...
Example: JSP Expression
<!DOCTYPE html>
<html>
<head><title>JSP Page</title></head>
<body> <h1>JSP Expression</h1>
<UL>
<li>Current time: <%= new java.util.Date() %> </li>
<li>Server: <%= application.getServerInfo() %> </li>
<li>Session ID: <%= session.getId() %> </li>
</UL>
</body> </html>
Comparing JSP and Servlets
JSP Servlet
JSP is a web page scripting language that can Servlets are already compiled which also create
generate dynamic content dynamic web content
JSP runs slower compared to servlet as it takes Servlets run faster compared to JSP.
compilation time to convert into java Servlets
It’s easier to code in JSP than in Java Servlets. Its little much code to write here.
In MVC, jsp act as a view. In MVC, servlet act as a controller.
JSP are generally preferred when there is not servlets are best for use when there is more
much processing of data required. processing and manipulation involved.
The advantage of JSP programming over There is no such custom tag facility in servlets.
servlets is that we can build custom tags which
can directly call Java beans.
We can achieve functionality of JSP at client There are no such methods for servlets.
side by running JavaScript at client side.
JSP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Reading Three Request Parameters</TITLE> </HEAD>
<BODY>
<H1>Reading Three Request Parameters</H1>
<UL>
<LI><B>param1</B>:
<%= request.getParameter("param1") %>
<LI><B>param2</B>:
<%= request.getParameter("param2") %>
<LI><B>param3</B>:
<%= request.getParameter("param3") %>
</UL>
</BODY></HTML>
Writing Scriptlets
Scriptlet Tag allows to write java code inside JSP page
Scriptlet tag implements the _jspService method functionality by
writing script/java code.
Scriptlets have the following form:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as
do expressions (request response, session, out, etc.). explicitly
sending output to the resultant page, out variable is used
Example of scriptlet( )
<html>
<head>
<title>My First JSP Page</title>
</head>
<% int count = 0; %>
<body>
Page Count is
<% out.println(++count); %>
</body>
</html>
Using Scriptlets to make parts of jsp
conditional
Insert 1 to many lines of java code
Key to this approach are the facts that
(a) code inside a scriptlet gets inserted into the resultant servlet’s
_jspService method (called by service) exactly as written and
(b) that any static HTML (template text) before or after a scriptlet
gets converted to print statements.
Using Declaration
A JSP declaration lets you define methods or fields that get inserted
into the main body of the servlet class (outside the _jspService
method)
Declaration is made inside the servlet class but outside the service
method.
A declaration has the following form:
<%! Field or Method Definition %>
<BODY>
<% if (Math.random() < 0.5) { %>
<H1>Have a <I>nice</I> day!</H1>
<% } else { %>
<H1>Have a <I>lousy</I> day!</H1>
<% } %>
</BODY>
if (Math.random() < 0.5) {
out.println("<H1>Have a <I>nice</I> day!</H1>");
} else {
out.println("<H1>Have a <I>lousy</I> day!</H1>");
}
Overuse of this approach can lead to JSP code that is hard to understand and maintain.
<html>
<head> <title>My First JSP Page</title>
</head>
<%! int count = 0; %>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>
JSP declarations can contain field (instance variable) definitions, method definitions,
inner class definitions, or even static initializer blocks: anything that is legal to put inside
a class definition but outside any existing methods.
Declarations almost always contain field or method definitions.
<H1>Some Heading</H1>
<%!
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");
}
%>
<%= randomHeading() %>
Declaration Example
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
Controlling the Structure of
generated servlets
The JSP page directive
JSP directive affects the overall structure of the servlet that results from the JSP
page.
The jsp directives are messages that tells the web container how to translate a
JSP page into the corresponding servlet.
Syntax:
i) <%@ directive attribute="value" %>
ii) <%@ directive attribute1="value1"
attribute2="value2"
................
attributeN="valueN" %>
Types of directive
In JSP, there are three types of directives:
page,
include, and
taglib
The JSP page directive
The page directive
controls the structure of the servlet by importing classes,
customizing the servlet superclass,
setting the content type
page directive can be placed anywhere within the document
The JSP page directive
The include directive
inserts a file into the servlet class at the time the JSP file is translated into a servlet.
An include directive should be placed in the document at the point at which you want the file to
be inserted.
The taglib directive
which can be used to define custom markup tags;
The page directive lets you define one or more of the following case-sensitive attributes:
import,
contentType,
isThreadSafe,
session,
buffer,
autoflush,
extends,
info,
errorPage,
isErrorPage, and language
import attribute
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.
Use of the import attribute takes one of the following
two forms:
1. <%@ page import="package.class" %>
2. <%@ page import="package.class1,...,package.classN" %
Example:
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
• The import attribute is the only page attribute that is allowed to
appear multiple times within the same document
• Although page directives can appear anywhere within the
document, it is traditional to place import statements either near
the top of the document
contentType Attribute
The contentType attribute sets the character encoding
for the JSP page and for the generated response
page. The default content type is text/html,
charset=ISO-8859-1" which is the standard content
type for HTML pages
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
Session Attribute
The session attribute controls whether or not the page participates in HTTP
sessions.
Use of this attribute takes one of the following two forms:
<%@ page session="true" %> <%-- Default --%>
<%@ page session="false" %>
A value of true indicates that the predefined variable session (of type
HttpSession) should be bound to the existing session if one exists; otherwise,
a new session should be created and bound to session.
A value false means that no sessions will be used automatically and
attempts to access session variable
<%@ page session="true" %>
<html>
<head><title>session </title></head>
<body>
<h3>Hello this is a session page directiv
example.</h3>
<%
out.print("Session id:" +
session.getId());
%>
</body>
</html>
isThreadSafe
The isThreadSafe attribute controls whether or not the servlet that
results from the JSP page will implement the SingleThreadModel
interface.
Use of the isThreadSafe attribute takes one of the following two
forms:
<%@ page isThreadSafe="true" %> <%!-- Default --%>
<%@ page isThreadSafe="false" %>
isThreadSafe="true", creates multiple objects for the same JSP
file when requested by multiple clients. Each client is served with a
separate _jspService() method
isThreadSafe="false", allows the container to create one Servlet
object for each client requesting the same JSP.
Buffer attribute
The buffer attribute specifies the size of the buffer used by the out
variable, which is of type JspWriter (a subclass of PrintWriter). Use of
this attribute takes one of two forms:
<%@ page buffer="sizekb" %>
<%@ page buffer="none" %>
Servers can use a larger buffer than you specify, but not a smaller
one.
For example, <%@ page buffer="32kb" %> means the document
content should be buffered and not sent to the client until at least 32
kilobytes have been accumulated or the page is completed.
The default buffer size is server specific, but must be at least 8
kilobytes.
Autofulsh attribute
The autoflush attribute controls whether the output buffer should be
automatically flushed when it is full or whether an exception should be raised
when the buffer overflows.
Use of this attribute takes one of the following two forms:
<%@ page autoflush="true" %> <%-- Default --%>
<%@ page autoflush="false" %>
A value of false is illegal when also using buffer="none".
Extends Attribute
The extends attribute specifies a superclass that the generated servlet
must extend.
For example, the following directive directs the JSP translator to generate
the servlet such that the servlet extends somePackage.SomeClass
<%@ page extends="package.class" %>
info
The info attribute defines a string that can be retrieved from the serv
means of the getServletInfo method.
Use of info takes the following form:
<%@ page info="Some Message" %>
errorPage
The errorPage attribute specifies a JSP page that should process any exceptions (i.e.,
something of type Throwable) thrown but not caught in the current page.
It is used as follows:
<%@ page errorPage="Relative URL" %>
The exception thrown will be automatically available to the designated error page by
means of the exception variable.
iserrorPage and language
Any JSP file declared with isErrorPage (and set to a value of
true), is capable to receive exceptions from other JSP pages.
Implicit object exception is available to these pages only (set
with true).
Default value is false.
<%@ page isErrorPage="true" %>
<%@ page isErrorPage="false" %> <%!-- Default --%>
It should be noted that errorPage and isErrorPage are used in
combination with "exception" object.
language
The language attribute is intended to specify the scripting language
used, as below
<%@ page language="java" %>
since java is both the default and the only legal choice
isElignore attribute
The isELIgnored attribute takes boolean value of true or false as input.
If isELIgnored is true, then any Expression Language in JSP is ignored.
The default value of isELIgnored is false.
The example below illustrates the usage of isELIgnored attribute of page directive.
<%@ page isELIgnored="false" %>
<%@ page isELIgnored="true" %>
include directive
The include directive tells the Web Container to copy everything in the
included file and paste it into current JSP file.
Syntax: <%@ include file="filename.jsp" %>
taglib directive
The taglib directive is used to define tag library that the
current JSP page uses. A JSP page might include several
tag library
JavaServer Pages Standard Tag Library (JSTL), is a collection
of useful JSP tags, which provides many commonly used
core functionalities.
Action Tags
Action tags
The action tags are used to control the flow between pages and to use Java Bean.
These tags are used to remove or eliminate scriptlet code from JSP page because
scriplet code are technically not recommended nowadays.
It's considered to be bad practice to put java code directly inside your JSP page.
Standard tags begin with the jsp: prefix.
There are many JSP standard Action tag which are used to perform some specific
task.
JSP action tags
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
Uses Bean Class
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include
mostly.
jsp:fallback can be used to print the message if plugin is working. It is
used in jsp:plugin.
Include action tag
Definition
Includes a page at the given location in the main
page
Syntax:
<jsp:include page =“{ page_to _include}”
flush=“true” />
Jsp action: include directive vs
include action
jsp:forward
The jsp:forward action tag is used to forward the request to another resource it
may be jsp, html or another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeU
RL />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL ">
<jsp:param name="param_name" value="param_value /
>
</jsp:forward>
jsp:param and jsp:params Elements
Definition
Pass parameters to the included/forwarded page
Syntax:
<jsp:include page =“{page_to_include}” flush=“true”>
<jsp:param name=“{param_name}" value=“{param_value }”/>
</jsp:include>
<jsp:forward page =“{page_to_forward}” flush=“true”>
<jsp:param name=“{param_name}" value=“{param_value }”/>
</jsp:forward>
<jsp:include page =“{page_to_include}” flush=“true”>
<jsp:params>
<jsp:param name=“{param_name}" value=“{param_value }”/>
<jsp:param name=“{param_name}" value=“{param_value }”/>
</jsp:params>
</jsp:include>
jsp:fallback Element
jsp:fallback element provides alternative text to browsers that do not support
OBJECT or EMBED.
This element is used the same way as alternative text placed within an APPLET
element
<jsp:plugin type=“applet”
code=“MyApplet.class” width=“450” height=“350”>
<jsp:fallback>
<B>Error: this example requires java.</B>
</jsp:fallback>
</jsp:plugin>
Including Applets for the Java Plug-In
The jsp:plugin element instructs the server to build a tag appropriate for applets that use the
plug-in.
The jsp:plugin Element
The simplest way to use jsp:plugin is to supply four attributes
type
code
width
height
The attribute names are case sensitive, and single or double quotes are always required
around the attribute values.
<APPLET CODE=“MyAppplet.class”
WIDTH=475 HEIGHT=350>
</APPLET>
With
<jsp:plugin type=“applet”
code=“MyApplet.class”
width=“475” height=“350”>
</jsp:plugin>
The jsp:plugin element has a number of other optional attribute
type
code
width
height
codebase
align
hspace
vspace
archive
name
title
Why Use Beans
Using separate Java classes instead of embedding large amounts
of code directly in JSP pages.
Beans are regular Java classes that follow some simple
conventions defined by the JavaBeans specification; beans
extend no particular class, are in no particular package, and use
no particular interface.
Use of JavaBeans components provides three advantages over
scriptlets and JSP expressions that refer to normal Java classes.
No Java syntax
Simpler object sharing
Convenient correspondence between request parameters and
object properties.
JavaBean
A JavaBeans component is a Java class with the following features.
A no-argument constructor.
Properties defined with accessors and mutators(getter and setter method).
Class must not define any public instance variables.
The class must implement the java.io.Serializable interface.
jsp:useBean
Using a javaBean in JSP Page
Javabeans can be used in any JSP page using the <jsp:usebean> tag
For example:
<jsp:useBean id=“bean name”
class=“qualified path of bean”
scope=“page | request |
application |session”>
The <jsp:useBean> is a way of declaring and initializing the actual bean object.
Syntax:
<jsp:useBean
<jsp:useBean id = "beanName" class = "className"
scope = "page | request | session | applicatio
jsp:getProperty
jsp:getProperty. This element reads and outputs the value of a bean prope
Reading a property is a shorthand notation for calling a method of the form
getXxx. This element is used as follows:
<jsp:getProperty name=“beanName”
property=“propertyName” />
jsp:setProperty
jsp:setProperty. This element modifies a bean property (i.e., calls a method of the form
setXxx).
It is normally used as follows:
<jsp:setProperty name="beanName"
property="propertyName"
value="propertyValue" />
There are several ways to use jsp:setProperty, but the best is with property =“*”
Scope (Visibility)
Page
(Least
Visible)
Request
Session
Application (Most Visible)
Scope
<jsp:useBean ... scope="page" />
‘page’ scope means, the jsp object can be accessed only from within the same page where it was created.
Jsp implicit objects out, exception, response, have page scope
• <jsp:useBean … scope=“request”/>
o Can access from any page
• <jsp:useBean ... scope="session" />
• Accessible from pages that belong to the same session.
• <jsp:useBean ... scope="application" />
• Can be accessed from any pages across the application
Including external file
JSP has three main capabilities for including external pieces into a JS
document:
The jsp:include action
The include directive
The jsp:plugin action
Including Pages at Request Time:
The jsp:include Action
Enter jsp:include, a portable mechanism that lets you insert any of the following into the
JSP output:
The content of an HTML page.
The content of a plain text document.
The output of JSP page.
The output of a servlet
The jsp:include action includes the output of a secondary page at the time the main page is
requested.
The jsp:include action
include the output of a page at request time.
Advantage
it saves you from changing the main page when the included pages change.
Disadvantage
is that since it includes the output of the secondary page, not the secondary
page’s actual code
The include directive
insert JSP code into the main page before that main page is translated into a servlet.
Advantage
Powerful
the included code can contain JSP constructs such as field definitions and content-type
settings that affect the main page as a whole.
Disadvantage
hard to maintain
The jsp:plugin action
server-side Java, client-side Java in the form of Web-embedded
applets continues to play a role, especially within corporate intranets.
The End
Jestin Johnson
1AY18MCA12