Java Training
Java Server Pages (JSP)
Written by Jeff Smith
What is JSP -1
JSP (Java Server Pages) is a server side scripting
technology that is similar to ASP (Active Server Pages) and
PHP is many respects. But where ASP relies on the
windows specific COM standard for embedded objects (e.g.
ADO), JSP uses platform neutral java beans.
While ASP scripts are written in either VBScript (the default)
or JScript, JSP scripts are written in Java
What is JSP -2
When a browser requests a page with a '.jsp' extension, the
JSP container on the web server runs the script as a servlet
(each instance in a separate thread), after checking to see
whether the JSP page needs compiling.
Tomcat is a popular (and free) JSP/servlet container
JSP pages are generally a mixture of standard HTML tags
and special JSP tags
Multiple (simultaneous) requests for the same JSP page
result in multiple threads being created (not multiple
processes). Since threads require significantly fewer
resources to create than processes, JSP pages are very
efficient.
What is JSP -3
Some JSP containers support "in process" execution which
allows the JSP servlet to run as part of the HTTP server
itself, which results in even greater efficiency.
By implementing JSP pages as compiled servlets which run
in multiple threads, JSP scales upwards quite well making
it's performance compare very favorably with other server
side technologies such as ColdFusion, CGI/C++, and ASP.
JSP Scriptlets -1
You can imbed Java code in a JSP (this code is called a
scriptlet)
Note: this is similar to the way it is done in ASP and PHP
You put your Java code between <% and %> tags
To display a Java value in your HTML, you use the <%= tag
e.g. <%= myJavaString %>
For example, the following code would check for a
parameter called username and if it exists, it would assign
that parameter to the variable userName and display it on
the page.
JSP Scriptlets -2
<HTML>
<BODY>
<%
String userName = request.getParameter("userName");
if ((userName == null) || (userName.length() < 1))
userName = "guest";
%>
<b>
Welcome to our website, <%= userName %>
</b>
</BODY>
</HTML>
JSP Scriptlets -3
You can test this JSP by saving it to disk with a .JSP
extension and placing it in a Tomcat context (i.e., a
webapps subdirectory). For example:
c:\Tomcat5\webapps\mywebapp\test.jsp
Note that in the screenshot above, I passed in the
parameter (userName=Jeff) in my URL.
JSP Scriptlets -4
If I don't pass in a userName parameter, I would get the
"guest" message instead.
JSP Scriptlets -5
You can write a Java loop and have it dynamically generate
HTML like so
<%
for (int i=0; i < 10; i++)
{
%>
<b>Loop counter i=</b>
<%= i %><br>
<%
}
%>
JSP Scriptlets -6
Here is the resulting HTML in a browser:
JSP Scriptlets (import) -7
Use the page import directive to import a class into your
JSP (for example, your page may require java.io.*).
<%@ page import="java.io.*, java.util.*" %>
JSP Scriptlets (summary)
Writing JSP scriptlets is quick and easy. But tightly coupling
the java code and HTML in the same file results in two
disadvantages:
1. The Java code cannot be easily reused in other pages
2. The presentation (HTML) and implementation (Java)
cannot be worked on separately. Often times Java
programmers aren't the best web design people (and
many web page designers often don't know Java).
Scriptlets Exercise
Create a login web page using JSP. The user should type in
his username and password into an HTML form. When the
user clicks on a "login" button, this information should be
sent to a JSP that validates the login using scriptlet code.
If the user enters (‘noaa', ‘noaa1') for his
username/password, a page should return saying he is
logged into the system.
Any other login should return a page saying "Access
denied".
JavaBeans -1
As an alternative to scriptlets, you can separate your HTML
from your Java code by writing JavaBeans and using the
JSP tags to access the bean from your HTML.
A JavaBean is simply a class that
1. has a no argument constructor
2. uses getter and setter methods to access all fields
3. implements the Serializable interface
4. can optionally use events to communicate with other
beans (more on this later on)
JavaBeans -2
JavaBeans enable component based software development
using visual tools (for example, designing a Swing user
interface using JBuilder or NetBeans)
Visual tools can persist JavaBeans state (e.g. setting
properties in a GUI development tool) because JavaBeans
implement the serialization interface
JBuilder and NetBeans have a "form designer" that enables
you to "drop" JavaBean controls onto a form and then
manipulate them
JavaBeans (JBuilder) -3
JavaBeans (JBuilder) -4
The JBuilder form designer allows you to write event
procedures for JavaBean components by clicking on a
component (to select it) and then going to the events tab
and dbl-clicking on an desired event procedure.
JavaBeans (JBuilder) -5
We'll talk more about JavaBeans and developing GUI
applications in a later section of slides
Remember that JavaBeans are not restricted to being GUI
components--almost any class can be written as a
JavaBean and utilized by JSP. For example
JSP/Servlet based web applications
Java Swing and SWT graphical user interfaces
JSPs with JavaBeans -1
If you separate your HTML from your Java code by writing
JavaBeans, you could create a LoginBean class that
creates a single property (username) which is defaulted to
"guest" in the constructor.
(see next slide)
JSPs with JavaBeans -2
package gov.noaa.login;
public class LoginBean implements java.io.Serializable
{
private String username;
public LoginBean() //constructor takes no arguments
{ this.username = "guest"; } //assign default value
public String getUsername()
{ return username; }
public void setUsername(String username)
{ this.username = username; }
}
JSPs with JavaBeans -3
The JSP page which uses this JavaBean might look like:
<HTML>
<BODY>
<jsp:useBean id="login" scope="session"
class="com.cexp.wms.login.LoginBean"/>
<jsp:setProperty name="login" property="username"
value="jsmith"/>
<b>
Welcome to our website,
<jsp:getProperty name="login" property="username"/>
</b>
</BODY>
</HTML>
JSPs with JavaBeans -4
The <jsp:useBean> tag declares the bean to be used with
this page, and identifies this bean as "login".
The <jsp:setProperty> tag provides access to the
"username" property and assigns it the value of the "jsmith"
parameter passed into the page via a URL query string.
This invokes the setUserName() method inside the class
Another example (code on next slide) -- if the URL
requesting this page was
'http://www.mydomain.com/login.jsp?username=Jeff',
the query string is "username=Jeff"
the following HTML would appear in the user's browser:
Welcome to our website, Jeff
JSPs with JavaBeans -5
<jsp> tag attributes can be in double quotes or single
quotes (just like HTML form fields)
You can also imbed scriplet code in a <jsp> tag to access
form fields:
<HTML>
<BODY>
<jsp:useBean id="login" scope="session"
class="com.cexp.wms.login.LoginBean"/>
<jsp:setProperty name="login" property="username"
value='<%= request.getParameter("username") %>'/>
Welcome to our website,
<jsp:getProperty name="login" property="username"/>
</BODY>
</HTML>
JSPs with JavaBeans -6
To test this page, I compiled the Java class and copied to a
Tomcat context called wms (i.e. /webapps/wms)
JSPs with JavaBeans -7
After restaring Tomcat, I invoked the JSP from my web
browser:
JSPs with JavaBeans -8
Tomcat Issue
When you recompile your JavaBean class, Tomcat won't
pick up the change until you restart (bounce) Tomcat.
Setting "reloadable=true" won't make any difference
(although this might work with Tomcat 6—I haven’t
tested this yet)
This is kind of a pain
When you only change the JSP file itself, you don't have
to bounce Tomcat.
Any Java scriptlets (imbedded Java) are
automatically recompiled
JSPs with JavaBeans (summary)
The drawback of using JavaBeans is that it requires more
upfront time to write the bean class and to write the
separate HTML file.
However, by isolating the Java code (implementaion) from
the HTML (presentation) we
1. Create a bean which can reused in other JSP pages
2. Make it possible to have one person write the bean and
a different person (perhaps a non-Java web designer) to
create the layout without worrying about overwriting the
other person's code.
Real-world, complex, websites are written using this
methodology--the Java code is separated from the HTML
presentation
JavaBeans Exercise
Create a login web page using JSP. The user should type in
his username and password into an HTML form. When the
user clicks on a "login" button, this information should be
sent to a JSP that validates the login using a separate
JavaBean class.
If the user enters (‘noaa', ‘noaa1') for his
username/password, a page should return saying he is
logged into the system.
Any other login should return a page saying "Access
denied".
JSPs and Servlets -1
In many web applications, HTML forms are submitted to a
Servlet which invokes application logic (in separate classes)
and based on this processing returns different JSP pages.
Some web apps use a Servlet for authentication control.
This Servlet could contain the code for authenticating the
user before allowing them to view certain pages.
Unauthenticated users could be detoured to a login
page.
It is better to put this login in one place (an
authentication Servlet) than in every JSP page.
JSPs and Servlets -2
A Servlet can simply redirect output to a JSP (or any other
source) via the response.sendRedirect() method. For
example, you might have the following code in your Servlet:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
if (...some condition...)
response.sendRedirect("http://someURL/di/err.jsp");
}
JSPs and Servlets -3
Sample Servlet / JSP architecture
Original request handled by Servlet
Servlet authenticates user, does database query and/or
executes application logic
Results are placed in JavaBeans
Request is forwarded to JSP for formatting/display
JSPs and Servlets -4
To Forward (or Dispatch) a request form a Servlet to a JSP
use the RequestDispatcher object
RequestDispatcher can forward a request (passing the
request and response objects)
For example, your Servlet could read a request
parameter to determine which JSP it should forward to
JSPs and Servlets -5
Here's an example of forwarding a request from a Servlet to
a JSP
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String url = "/inventory.jsp"; //relative URL
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
The inventory.jsp file referenced in the relative URL will
need to reside in the root dir of your web context (e.g. the
"wms" directory).
Servlet/JSP Exercise
Modify your JavaBeans exercise so that your HTML login
form action points to a Servlet named LoginServlet.
This Servlet should validate the login and if it succeeds, it
should return a "success" JSP page.
If the login fails, the Servlet should return a "failure" JSP
page.
Initialization & Destruction -1
Like Servlets, JSP pages allow you to execute initialization
code in a special method.
The initialization code is executed
the first time the JSP page is requested
The destruction code is executed when
the JSP container is shutting down
or when the JSP container unloads a JSP to
conserve resources (and when the JSP hasn't been
called recently)
These two code sections would be a good place to establish
and close a database connection pool
Initialization & Destruction -2
To add this code to your page, you write something like:
<%! public void jspInit()
{
//put your initialization code here
}
public void jspDestroy()
{
//put your cleanup code here
}
%>
JSP Implicit Objects -1
Implicit objects are just objects that are available in every
JSP (as a programmer, you can access these objects).
config javax.servlet.ServletConfig Servlet config data
page javax.servlet.jsp.HttpJspPage servlet instance of page
request javax.servlet.http.HttpServletRequest request data & parameters
response javax.servlet.http.HttpServletResponse response data
out javax.servlet.jsp.JspWriter output stream for page
session javax.servlet.http.HttpSession user specific session data
application javax.servlet.ServletContext shared data (all pages)
pageContext javax.servlet.jsp.PageContext context data/page exec.
exception java.lang.Throwable uncaught exception
JSP Implicit Objects -2
Implicit objects that can persist values (attributes) to enable
state information to be transferred from one JSP to another
request
session
application
pageContext
Common attribute persistence methods
setAttribute(key, value) -- assoc a key with a value
getAttributeNames() -- gets list of all attributes
getAttribute(key) -- gets the attribute value for key
removeAttribute(key) -- removes attribute from list
JSP Implicit Objects -3
For example, one JSP in a web application could save a
color by using the setAttribute() function
<%
String myColor = "Green";
application.setAttribute("color", myColor);
%>
Another JSP in this application could read this attribute
<%
String color =
(String)application.getAttribute("color");
%>
The color was: <% color %>
Request Implicit Object
The request object contains all the information associated
with the HTTP request (just like with Servlets)
HTML form fields (parameters)
requested URL
cookies
headers
See the javadocs for HttpServletRequest
<%
String username = request.getParameter("username");
%>
Response Implicit Object
The response object represents the response that will be
sent back to the user (just as in Servlets)
setContentType() -- html or other MIME type
addCookie(cookie)
sendRedirect(url) -- redirects response to another URL
See the javadocs for HttpServletResponse
<%
response.setContentType("text/html");
out.println("<HTML>Greetings, Earthlings</HTML>");
%>
Out Implicit Object
The out object represents the output stream for the page.
The out object is an instance of javax.servlet.jsp.JspWriter
JspWriter methods
println()
clear() -- clears the contents of the output buffer
newLine() -- inserts a line separator
close() -- closes the output stream
See the javadocs for JspWriter
<%
response.setContentType("text/html");
out.println("<HTML>Greetings, Earthlings</HTML>");
%>
Session Implicit Object -1
The session object represents a user's current session
Only available if the session attribute of the page
directive is specified in the JSP
<%@ page session="true"%>
When a session has been created, all requests by the
session user are considered to be part of the session
the session times out when no new requests have been
received by the user for a certain length of time
The session object is primarily used to persist state
information between HTTP requests (through the use of
attribute values)
Session Implicit Object -2
The following code creates a UserLogin object and adds this
object to the session
<%
UserLogin user = new UserLogin(uname, pwd);
session.setAttribute("userlogin", user);
%>
After the above code executes, another JSP scriptlet (on the
same page or a different page) could retrieve the login data
by calling the session.getAttribute() method:
<%
UserLogin user =
(UserLogin)session.getAttribute("userlogin");
%>
Current user: <%= user.getUname() %>
Application Implicit Object -1
JSP pages are grouped into applications based on their
URLs.
By default, most JSP containers treat the first directory
name in a URL as an application. For example, the following
JSP pages would be considered to be part of a single
application
http://localhost:8080/wms/inbound/x.jsp
http://localhost:8080/wms/outbound/y.jsp
Application grouping can also be set explicitly in web
application descriptor files.
Application Implicit Object -2
You might use the application object to store information
(objects) you want to be available to all JSPs in the
application
For example, you might store a database connection pool
object in the application object:
<%!
public void jspInit()
{
ConnectionPool conPool = new ConnectionPool(...);
application.setAttribute("conPool", conPool);
}
%>
JSP Error Pages -1
The exception object is used to provide exception handling
in your JSP application
It enables you to specify a page that will be returned to a
user in the event an unhandled exception is thrown. So you
have two pages
1. Regular JSP that may throw an exception
2. Error JSP page that is returned in the event the regular
JSP page threw an exception
JSP Error Pages -2
Here is the "regular" JSP page (regularPage.jsp) that
generates the exception
regularPage.jsp:
<html>
<body>
<%@ page errorPage="myErrorPage.jsp" %>
<h1>Attempting to divide by zero</h1>
<%
double x = 55/0;
%>
<h1>Made it here</h1>
</body>
</html>
JSP Error Pages -3
Here is the file, myErrorPage.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
<b>The following exception was thrown:</b><br>
<%= exception.getMessage() %>
</body>
</html>
JSP Error Pages -4
Here's what we see in the browser:
JSP Error Pages -5
You can define a single, custom, JSP error (exception) page
and use it in all the JSPs in your web application
This enables you to create a consistent and attractive look
for your error pages.
Your error pages could also execute code that logs the
exception message to a log or a database table
Servlets in your web application can also use this JSP error
page
JSP Error Pages and Servlets -1
You can forward a Servlet exception on to your JSP error
page too.
You need to add this to your web.xml (assuming you’ve
created an error page named ErrorPage.jsp)
<web-app>
... some servlet mappings…
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/ErrorPage.jsp</location>
</error-page>
</web-app>
JSP Error Pages and Servlets -2
For example, the following code generates an exception and
forwards it to ErrPage.jsp in the event that no password was
passed into the Servlet (presumably from an HTML form).
String password = request.getParameter("password");
if (password == null)
request.setAttribute("javax.servlet.jsp.jspException",
new Exception("missing password"));
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/ErrPage.jsp");
dispatcher.forward(request, response);
JSP Composite Pages-1
You can include "incomplete" JSPs in other JSPs. Why
would you do this?
For example, you might want to use a common header file
called header.jsp in all your pages. You could also include a
common footer page:
<html>
<body>
<jsp:include page="header.jsp" flush="true">
...rest of page goes here...
<%@ include file="footer.jsp" %>
</body>
</html>
header.jsp might contain code for generating a site menu
that you want on the top of every page in your website
Web Application Architectures-1
You can create a Page Centric architecture which consists
entirely of JSPs.
Some JSPs do the presentation
Other JSPs encapsulate the application logic
either through scriptlets or JSPs and JavaBeans
Advantages
Simple architecture, good for prototypes
Fast to develop for people proficient in Java and HTML
Disadvantages
More difficult to maintain a complex web application
(some coupling of Java and HTML is inevitable)
More difficult to enforce flow control (web users can
invoke an JSP file they want in their browser in any order
Web Application Architectures-2
A Servlet Centric architecture
Servlets do flow control (all form actions point to one or
more servlets)
Servlets and associated classes do the application logic
Servlets only return JSPs to the web browser (i.e., all
presentation is in the form of JSPs)
Advantages
More flexible and maintainable for larger websites
Since there isn't any application logic in the JSPs, they
are "thinner" and easier for non-Java people to develop
A single Servlet can manage user logins and flow
Disadvantages
Slightly more complex architecture since we've added
Servlets to the mix
Web Application Architectures-3
Servlet Centric Architecture
Web Application Architectures-4
Struts and JSF (Java Server Faces) are popular open
source Java frameworks for building web applications.
Based on the MVC (model view controller) design pattern
Advantages
It makes it easier to organize, control flow, and maintain
large web applications that contain Servlets, JSPs and
custom Struts tag libraries
Disadvantages
More complex architecture (since you now have Struts or
JSF in the mix). You also have to learn how Struts works.
:-)
more on Struts, JSF, and tag libraries later on...
E-commerce Exercise -1
Design a website using Servlets, JSPs, JDBC (possibly using
SQLExecutor) to compete with Apple's iTunes Music Store
Customers should be able to browse/search songs by
genre: rap, classical, rock
song name
artist
A customer should be able to "purchase" songs by selecting the ones
they want and then pressing a "Buy Now" button. A new page should
appear that prompts the customer for the following information:
name on credit card (CC), CC type, CC num, CC Exp, email address
The website should return an error page if the user omitted any of
this required CC information
If all the required information was provided, return a confirmation
page for the purchase (what they purchased, how much it cost, the
date, etc.). Also send out this information in a confirmation email.
After purchasing a song, a customer should receive a link to that
enables him to download the song to his PC
All song purchases should be recorded in the database
E-commerce Exercise -2
Oh No! It’s Too Complicated! How Do I Start?
Phase 1--just do the search-for-songs stuff first (don’t
worry about enabling users to purchase songs)
You’ll need to create a script to generate your database.
This database should probably have a “song” table
You’ll need to insert some song records into your DB
You’ll need a web page where people can choose the
genre, song name, or artist. The form action should point
to your servlet
Your Servlet should read the request from the web page
and do a database search for the matching song(s).
Next, it should pack the matching song(s) records into
Java Beans and forward this information to a JSP for
display.
E-commerce Exercise -3
Phase 2
When returning the songs that match the user’s query,
you need to add the ability to select songs for purchase
When the user has selected some songs and pressed
some “Purchase” button, you’ll need to forward the songs
selected for purchase to your servlet.
The servlet can pack these selected songs into Java
Beans and forward them to a JSP which totals the cost
and prompts the user for their credit card information
This JSP’s form action should be a servlet (the same
servlet?) that validates their credit card information and
sends back a confirmation page (or an error page if they
left out required information)
Easy, huh?
E-commerce Exercise -4
Extra Credit:
Create an admin login page that enables an administrator to log in
(with the appropriate password). If the login is successful, display a
admin page with all the sales information in a slick looking HTML
table
Put an HTML form (with a textarea control) on the admin page that
enables the administrator to paste in some HTML. When the
administrator clicks the "Send Email" button, an email message
should be constructed (with this HTML as the message part) and
this email should be sent to every customer who has purchased a
song in the past 7 days.