Vous êtes sur la page 1sur 63

Basic JSPs

Web Programming
Introduction
● In the previous chapter, we have learned how to produce
dynamic content for our users using Java technology
through the use of servlets.
● However, while Java developers can create sites with such
dynamic content using only servlets, there are several
disadvantages in doing so:
– Using only servlets to produce HTML content does not make
very maintainable or clean code.
– Using only servlets to produce HTML content assumes that the
developer is familiar with both Java & HTML.
● This is where JSP technology comes in handy.

Web Programming 2
What is JSP?
● Java Server Pages
● A servlet-based technology used in the web tier to present
both dynamic and static content.
● Text-based and contains mostly HTML template text
intermixed with tags specifying dynamic content.

Web Programming 3
Why JSP?
● Since JSPs are text documents much like HTML,
developers avoid having to format and manipulate a
possibly very long String to produce output. The HTML
content is now not embedded within a lot of Java code.
This makes it easier to maintain.
● JSPs are immediately familiar to anyone with knowledge of
HTML, with only the dynamic markup to learn. This
makes it possible for dedicated site designers to create
the HTML template of the site, with developers
processing it later to include the tags producing dynamic
content. This makes for ease of web page development.

Web Programming 4
Why JSP?
● JSPs have built-in support for the use of reusable software
components (JavaBeans). This not only lets developers
avoid possibly reinventing the wheel for each application,
having support for separate software components to
handle logic promotes separation of presentation and
business logic.
● JSPs, as part of Java's solution to web application
development, are inherently multi-platform and can be
run in any compatible servlet container, regardless of the
vendor or operating system.

Web Programming 5
Why JSP?
● Due to the way JSPs work, they do not need explicit
compilation by the developer. This compilation is done
for us by the servlet container. Modifications to JSPs are
also automatically detected and result in recompilation.
This makes them relatively simpler to develop.

Web Programming 6
Sample JSP
<TITLE>Welcome</TITLE>

<BODY>
<H1> Greetings!</H1> <br>

Thank you for accessing our site. <br>

The time is now <%= new java.util.Date()%>

</BODY>

</HTML>

Web Programming 7
Output of Sample JSP

Web Programming 8
Running the Sample JSP
● Using the IDE
– Assuming that a project already exists, simply place the JSP
file within the Web Pages folder within the Project view.

Web Programming 9
Running the Sample JSP
(Using the IDE continued)
– The specific JSP page can then be run from the IDE directly by
pressing Shift + F6.
– Alternatively, the web project can be packaged as a WAR file
and uploaded into a server. The JSP can then be accessed
by typing in the following URL:
http://[host]:[port]/[WEB_PROJECT_NAME]/[JSP_NAME]

Web Programming 10
Running the Sample JSP
● Using an Ant build file
– The JSP can also be run by packaging it into a WAR file using
a build tool, and then deploying the WAR file into a web
server.
After build script has executed, will contain the application in a directory structure recognized by
servlet containers.

After build script has executed, will contain the WAR file.
Used to contain whatever documentation is used by the dev team.
Directory under which all Java source files must be placed.
Directory containing all static content of the app (HTML, JSP), will be the basis of the document
root of your project.

Directory containing configuration files such as the deployment descriptor (web.xml),


tag library descriptors, etc.

● Following the development directory structure discussed in the earlier


chapter, our JSP file should be placed in the web directory.

Web Programming 11
JSP Lifecycle
● The servlet container manages JSPs in a similar manner as
it does to servlets: through the use of a well-defined
lifecycle.
● JSPs have a three-phase lifecycle:
– Initialization
– Service
– Destruction

Web Programming 12
JSP and Equivalent Servlet
● JSPs are compiled into an equivalent servlet class by the
server.
– It is this servlet class that handles all requests to the JSP page.
● If you wish to view the generated servlet class, installations
of Sun Application Server 8.1 places them in the
following directory:
${SERVER_HOME}/domains/domain1/generated/jsp/j2ee-
modules/
${WEB_APP_NAME}/org/apache/jsp

Web Programming 13
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase


implements org.apache.jasper.runtime.JspSourceDependent {

private static java.util.Vector _jspx_dependants;

public java.util.List getDependants() {


return _jspx_dependants;
}

public void _jspService(HttpServletRequest request, HttpServletResponse


response)
throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;


PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
Web Programming 14
try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html");
response.addHeader("X-Powered-By", "JSP/2.0");
pageContext = _jspxFactory.getPageContext(this, request,
response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;

out.write("<HTML>\n");
out.write("\n");
out.write(" <TITLE>Welcome</TITLE>\n");

out.write("\n");
out.write(" <BODY>\n");
out.write(" <H1> Greetings!</H1> <br>\n");
out.write("\n");
out.write(" Thank you for accessing our site. <br>\n");
out.write("\n");
out.write(" The time is now ");
out.print( new java.util.Date());
out.write("\n");
out.write("\n");
Web Programming 15
out.write(" </BODY>\n");
out.write("\n");
out.write("</HTML>");
}catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null)
_jspx_page_context.handlePageException(t);
}
} finally {
if (_jspxFactory != null)
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}

Web Programming 16
JSP and Equivalent Servlet
● It is not important to understand the code given.
● What is important here is to see that JSPs are handled just
like Servlets, even if it is not immediately obvious.
● JSPs vs servlets:
– JSPs are more text-oriented.
– Servlets allow the developer greater freedom with Java code .

Web Programming 17
JSP Syntax and Semantics
● Elements and Template Data
– Components of all JavaServer Pages can be divided into two
general categories:
● Elements: dynamically produced information
● Template data: static information that takes care of presentation
<%@ page import=“jave.util.Date” %>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<center>
<h1>Hello World! It's <%= new Date()%></h1>
</center>
</body>
</html>

Web Programming 18
JSP Syntax and Semantics
(Elements and Template Data continued)
– Two Types of Syntax:
● JSP Style: designed to be easier to the author
● XML Style: normal syntax modified to become XML-compliant and
preferred when using JSP authoring tools
– Choosing one syntax format over the other is just a matter of
preference and standardization.

Web Programming 19
JSP Syntax and Semantics
● Scripting Elements
– JSPs may be viewed as HTML or XML documents with
embedded JSP scripts. JSP scripting elements allow you to
insert Java code into the Servlet that will be generated from
the JSP page.
– The simplest way to make a JSP dynamic is by directly
embedding scripting elements into template data.
– JSP scripting elements:
● Scriptlets
● Expressions
● Declarations

Web Programming 20
Scriptlets
● Provide a way to directly insert bits of Java code in between
chunks of template data:
<% Java code; %>
– Just the same as writing normal Java code except that there is
no need for a class declaration.
– If you want to use the characters "%>" inside a scriptlet, write
"%\>" instead.
● Useful for embedding simple java codes
● No specific limit as to the complexity of Java codes
– Overusing scriptlets:
● Putting too heavy computation inside scriptlets is a code
maintainability issue.
● Using scriptlets extensively violates JSPs role of being primarily a
presentation layer component.
Web Programming 21
Scriptlets
● Simple println

Web Programming 22
Scriptlets
● For-Loop in a scriplet

Web Programming 23
Scriptlets
● Output of the For-Loop scriptlet

Web Programming 24
Scriptlets
(Output continued)
– Take note that the scriptlet itself is not sent to the client but only
its output. Try viewing the source of the jsp output you've
produced in your browser to understand this point. All you
should see are HTML tags plus the scriptlet output and
minus the scriptlet.
● The XML-compatible syntax for writing scriptlets is:
<jsp:declaration>
Java code;
</jsp:declaration>.

Web Programming 25
Expressions
● Provide a way to insert Java values directly into the output
<%= Java Expression %>
– It is actually short for out.println().
– Notice that a semicolon ( ; ) does not appear at the end of the
code inside the tag.
– Evaluated at run-time, converted to a string, and inserted in the
page.
● Since it is evaluated at run-time, expressions have full
access to information about the request.

Web Programming 26
Expressions
● A number of predefined variables, called implicit objects,
are made available to JSP authors to simplify
expressions. The most important ones are:
– request: the HttpServletRequest;
– response: the HttpServletResponse;
– session: the HttpSession associated with the request (if any)
– out: the PrintWriter (a buffered version of type JspWriter) used
to send output to the client
● Example:
Hostname: <%= request.getRemoteHost() %>

Web Programming 27
Expressions
● XML-compatible syntax:
<jsp:expression>
Java Expression
</jsp:expression>

Web Programming 28
Declarations
● Allow you to define methods or variables.
<%! Java Code %>
● Used to embed code just like scriptlets but declarations get
inserted into the main body of the servlet class, outside
of the _jspService() method processing the request.
– Advantage
● Code embedded in a declaration can be used to declare new
methods and global class variables.
– Disadvantage
● Code in declarations are not thread-safe.

Web Programming 29
Declarations
● Reminders in using the declaration tag:
– Before the declaration you must have <%!.
– At the end of the declaration, the developer must have %>.
– Code placed in this tag must end in a semicolon ( ; ).
– Declarations do not generate output but are used with JSP
expressions or scriptlets.
● Since declarations do not generate any output, they are
normally used in conjunction with JSP expressions or
scriptlets.

Web Programming 30
Declarations
● Example: AccessCountDeclaration.jsp

– This JSP is able to print out the number of visits by declaring a


class-wide variable accessCount, using a scriptlet to
increment the value of the number of page visits and an
expression to display the value.

Web Programming 31
Declarations
● Sample output of AccessCountDeclaration.jsp refreshed 4
times

Web Programming 32
AccessCountDeclaration_jsp.java

package org.apache.jsp.JSP;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class AccessCountDeclaration_jsp


extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {

private int accessCount = 0;

private static java.util.Vector _jspx_dependants;

public java.util.List getDependants() {


return _jspx_dependants;
}

public void _jspService (HttpServletRequest request, HttpServletResponse


response)
throws java.io.IOException, ServletException {

Web Programming 33
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;

try {

_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request,
response, null, true, 8192, true);

_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();

Web Programming 34
out = pageContext.getOut();
_jspx_out = out;
out.write("\n");
out.write("\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<title>Declaration Example</title>\n");
out.write("</head>\n");
out.write("<body>\n");
accessCount++;
out.write("Accesses to page since server reboot: \n");
out.print( accessCount );
out.write("\n");
out.write("</body>\n");
out.write("</html>\n");
out.write("\n");
out.write("\n");

} catch (Throwable t) {

if (!(t instanceof SkipPageException)){


out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();

Web Programming 35
if (_jspx_page_context != null)
_jspx_page_context.handlePageExcepti
on(t);

} finally {
if (_jspxFactory != null)
_jspxFactory.releasePageContext(_jspx_page_co
ntext);
}

Web Programming 36
Declarations
● XML-compatible syntax:
<jsp:declaration>
Java Code;
</jsp:declaration>

Web Programming 37
Template Text
● Use <\% to get <% in output.
● <%-- JSP Comment --%>
● <!-- HTML Comment -->
● All other non-JSP-specific text passed through to output
page

Web Programming 38
Predefined Variables
● JSP implicit objects are automatically declared by the JSP
container and are always available for use in expressions
and scriptlets.
– request: The instance of the
javax.servlet.http.HttpServletRequest object associated with
request of the client.
– response: The instance of the
javax.servlet.http.HttpServletResponse object associated
with response to the client.
– pageContext: The PageContext object associated with current
page.
– out: References the javax.servlet.jsp.JspWriter object which
may be used to write actions and template data in a JSP
page, similar to that of the PrintWriter object we used in the
servlet discussion. The implicit variable out is initialized
Web Programming 39
automatically using methods in the PageContext object.
Predefined Variables
(JSP implicit objects continued)
– session: An instance of a javax.servlet.http.HttpSession object.
It is equivalent to calling the
HttpServletRequest.getSession() method.
– application: The ServletContext is an instance of the
javax.servlet.ServletContext object. It is equivalent to calling
getServletConfig().getContext() method. This implicit object
is shared by all servlets and JSP pages on the server.
– config: The config implicit object is an instance of the
javax.servlet.ServletConfig object for this page. Same as
Servlets, JSPs have access to the parameters initially
defined in the Web Application Deployment Descriptor.

Web Programming 40
JSP Directives
● Messages to a JSP container
● Affect the overall structure of the servlet class
<%@ directive attribute="value" %>

<%@ directive attribute1="value1"


attribute2="value2"
...
attributeN="valueN" %>

– Note: Whitespaces after <%@ and before %> are optional.


● Do not produce any visible output when the page is
requested but they change the way the JSP Engine
processes the page.
● Give special information about the page to the JSP Engine.

Web Programming 41
JSP Directives
● Types:
– Page
– Include
– Taglib

Web Programming 42
Page Directive
● Defines the processing information for this page.
● Allows you to import classes, customize the servlet
superclass, and the like.
● Note that attributes are case-sensitive.

Web Programming 43
Web Programming 44
autoFlush When set to true, flushes the output <%@ page autoFlush = “true” %>
buffer when it is full.
isThreadSafe Indicates if the generated Servlet deals
with multiple requests. If true, a new
thread is started to handle requests
simultaneously. Default value is true.
info Developer uses info attribute to add <%@ page info = “jedi.org test page, alpha version “
information/document for a page. %>
Typically this is used to add author,
version, copyright and date info.
errorPage Defines the page that deals with errors. <%@ page errorPage = “/errors.jsp” %>
Must be URL to error page.
IsErrorPage A flag that is set to true to make a JSP
page a special Error Page. This page has
access to the implicit object exception

Web Programming 45
Page Directive
● XML syntax:
<jsp:directive.directiveType attribute=value />

– For example, the XML equivalent of:


<%@ page import="java.util.*" %>
is
<jsp:directive.page import="java.util.*" />

Web Programming 46
Include Directive
● Defines the files to be included in the page.
● Lets you insert a file into the servlet class during translation
time.
● Typically used for navigation, tables, headers and footers,
etc.
– Components that are common to multiple pages.
<%@ include file = "relativeURL" %>

Web Programming 47
Tag Lib Directive
● A collection of custom tags
● Defines the tag library to be used in the page
<%@ taglib uri = “tag library URI” prefix = “tag Prefix” %>
● Tells the container which markup in the page should be
considered custom code and what code the markup links
to
● Custom tags were introduced in JSP 1.1 and allowed JSP
developers to hide complex server side code from web
designers.

Web Programming 48
index.jsp

<%@ taglib uri="struts/template" prefix="template" %>

<template:insert template="/WEB-INF/view/template.jsp">
<template:put name="header" content="/WEB-INF/view/header.jsp" />
<template:put name="content" content="/WEB-INF/view/index_content.jsp" />
<template:put name="footer" content="/WEB-INF/view/footer.jsp" />
</template:insert>

Web Programming 49
JavaBeans in JSP
● The use of JavaBeans are not mandated in the JSP
specification.
● Provide useful functionality in that usage of JavaBeans can
greatly reduce the amount of scripting elements to be
found in a Java page.

Web Programming 50
JavaBeans
● Simple Java classes adhering to a certain coding standard:
– Provides a default, no-argument constructor
– Provides get and set methods for properties it wishes to expose

Web Programming 51
package jedi.beans;

public class User {


private String name;
private String address;
private String contactNo;

public User() {
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

Web Programming 52
public String getContactNo() {
return contactNo;
}

public void setContactNo(String contactNo) {


this.contactNo = contactNo;
}
}

Web Programming 53
How are JavaBeans used in
JSP?
● As a Data Transfer Object
– JavaBeans are more widely used in JSPs as objects that
transfer data from another source. In most applications,
actual processing is done in a servlet, not in a JSP. Only the
results of the passing are passed on to the JSP in the form
of one or more JavaBeans.
● As a Helper object
– In some small applications, it is not efficient to have a separate
servlet to process the data. In this case, it is better to place
the functionality inside JavaBeans which can be accessed
by the JSP.

Web Programming 54
JavaBeans-related JSP
Actions
● JSP defines standard actions that simplify the usage of
JavaBeans.
– <jsp:useBean>
– <jsp:getProperty>
– <jsp:setProperty>

Web Programming 55
<jsp:useBean>
● To use a JavaBeans component, the first thing to do is to
enable the use of a bean within the page through
instantiation, which we can do with this action.
● Attributes:
– id: This attribute specifies the name of the bean and how you
will refer to it in the page.
– scope : This attribute specifies the scope in which you want to
store the bean instance. It can be set to page (the default),
session, request, or application.
– class: This attribute specifies the Java class that the bean is
drawn from. If you have specified beanName, you do not
have to specify class.

Web Programming 56
<jsp:useBean>
(Attributes continued)
– beanName: This attribute specifies the name of a bean that is
stored on the server. You refer to it as you would a class (for
example, com.projectalpha.PowerBean). If you have
specified class, you do not need to specify beanName.
– type: This attribute specifies the type of scripting variable
returned by the bean. The type must relate to the class of the
bean.

Web Programming 57
<jsp:useBean>
● Sample Usage:
<jsp:useBean id="user" scope="session" class="jedi.bean.User"/>
– When the page encounters a useBean action, it first tries to see
if there is already a JavaBean instance of the given type
located in the given scope.
● If there is, the page will make use of that bean instance.
● If not, the container will automatically create a new bean instance
using the bean's default no-argument constructor and place that
bean in the given scope.
– If the above functionality were to be expressed as a scriptlet, it
would look like this:
<%
jedi.bean.User user =
(jedi.bean.User)session.getAttribute("user");
if (user == null) {
user = new User();
session.setAttribute("user", user);
58
} Web Programming
<jsp:useBean>
● Once a bean has been enabled using the jsp:useBean
action, it can be used inside the JSP page like any other
object instance using the name specified in the id
attribute.
– Example
<jsp:useBean id="user" scope="session"
class="jedi.bean.User"/>
<HTML>
<BODY>
Hello <%= user.getName() %> !!
</BODY>
</HTML>

Web Programming 59
<jsp:getProperty>
● Retrieves the value of a property inside a specified
JavaBean and outputs it immediately to the response
stream.
● Has two attributes:
– name: The name of the JavaBean whose property is to be
retrieved. This must have the same value as the id attribute
used in an earlier <jsp:useBean> action.
– property: The name of the property whose value will be
retrieved.
<jsp:getProperty name="user" property="name"/>
● If the developer wishes to be able to retrieve the value of a
JavaBean property without immediately placing it in the
output stream, there is no choice but to make use of
scriptlets or EL. 60
Web Programming
<jsp:setProperty>
● Allows developers to set the properties of a given
JavaBean without the developer having to write a line of
scriptlet code.
● Has the same attributes with the getProperty action, with
the addition of two more:
– value: The value to be set into the property. This can be either a
static value or an expression that can be evaluated at
runtime.
– param: Specifies the request parameter from which the
property will retrieve its value.
● Developers making use of this action must specify one of
either value or param attribute. Including both in the
action will cause an exception to be thrown.
Web Programming 61
Error Handling
● JSPs can make use of the page directive to specify a page
that will handle any uncaught exceptions.
– The errorPage attribute of the page directive can be passed a
relative URL to the JSP page designated as an error page.
– The page thus designated can set the isErrorPage attribute to
true. Doing so will give them access to an implicit object
named exception – this contains details about the exception
thrown.

Web Programming 62
A JSP page using the page directive to describe an error page that will be used for
unhandled exceptions:

<%@page errorPage="errorPage.jsp"%>
<HTML>
<%
String nullString = null;
%>

// call a method on the null object, so that an exception will be thrown and the error page
called
The length of the string is <%= nullString.length() %>
</HTML>

The designated error page:

<%@page isErrorPage="true"%>
<HTML>
<TITLE>Error!</TITLE>
<BODY>
<H1>An Error has occurred.</H1><br/>
Sorry, but an error has occurred with the page you were previously accessing. Please
contact any member of the support team, and inform them that <%=
exception.getMessage() %> was the cause of the error
</BODY>
</HTML>

Web Programming 63