19-Java Server Pages (JSP)

62
Java Training Java Server Pages (JSP) Written by Jeff Smith

Transcript of 19-Java Server Pages (JSP)

Page 1: 19-Java Server Pages (JSP)

Java TrainingJava Server Pages (JSP)

Written by Jeff Smith

Page 2: 19-Java Server Pages (JSP)

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

Page 3: 19-Java Server Pages (JSP)

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.

Page 4: 19-Java Server Pages (JSP)

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.

Page 5: 19-Java Server Pages (JSP)

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.

Page 6: 19-Java Server Pages (JSP)

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>

Page 7: 19-Java Server Pages (JSP)

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.

Page 8: 19-Java Server Pages (JSP)

JSP Scriptlets -4

If I don't pass in a userName parameter, I would get the "guest" message instead.

Page 9: 19-Java Server Pages (JSP)

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>

<%

}

%>

Page 10: 19-Java Server Pages (JSP)

JSP Scriptlets -6 Here is the resulting HTML in a browser:

Page 11: 19-Java Server Pages (JSP)

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.*" %>

Page 12: 19-Java Server Pages (JSP)

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).

Page 13: 19-Java Server Pages (JSP)

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".

Page 14: 19-Java Server Pages (JSP)

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)

Page 15: 19-Java Server Pages (JSP)

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

Page 16: 19-Java Server Pages (JSP)

JavaBeans (JBuilder) -3

Page 17: 19-Java Server Pages (JSP)

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.

Page 18: 19-Java Server Pages (JSP)

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

Page 19: 19-Java Server Pages (JSP)

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)

Page 20: 19-Java Server Pages (JSP)

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; }

}

Page 21: 19-Java Server Pages (JSP)

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>

Page 22: 19-Java Server Pages (JSP)

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

Page 23: 19-Java Server Pages (JSP)

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>

Page 24: 19-Java Server Pages (JSP)

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)

Page 25: 19-Java Server Pages (JSP)

JSPs with JavaBeans -7 After restaring Tomcat, I invoked the JSP from my web

browser:

Page 26: 19-Java Server Pages (JSP)

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

Page 27: 19-Java Server Pages (JSP)

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

Page 28: 19-Java Server Pages (JSP)

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".

Page 29: 19-Java Server Pages (JSP)

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.

Page 30: 19-Java Server Pages (JSP)

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");

}

Page 31: 19-Java Server Pages (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

Page 32: 19-Java Server Pages (JSP)

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

Page 33: 19-Java Server Pages (JSP)

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).

Page 34: 19-Java Server Pages (JSP)

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.

Page 35: 19-Java Server Pages (JSP)

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

Page 36: 19-Java Server Pages (JSP)

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

}

%>

Page 37: 19-Java Server Pages (JSP)

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

Page 38: 19-Java Server Pages (JSP)

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

Page 39: 19-Java Server Pages (JSP)

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 %>

Page 40: 19-Java Server Pages (JSP)

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");

%>

Page 41: 19-Java Server Pages (JSP)

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>");

%>

Page 42: 19-Java Server Pages (JSP)

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>");

%>

Page 43: 19-Java Server Pages (JSP)

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)

Page 44: 19-Java Server Pages (JSP)

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() %>

Page 45: 19-Java Server Pages (JSP)

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.

Page 46: 19-Java Server Pages (JSP)

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);

}

%>

Page 47: 19-Java Server Pages (JSP)

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

Page 48: 19-Java Server Pages (JSP)

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>

Page 49: 19-Java Server Pages (JSP)

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>

Page 50: 19-Java Server Pages (JSP)

JSP Error Pages -4

Here's what we see in the browser:

Page 51: 19-Java Server Pages (JSP)

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

Page 52: 19-Java Server Pages (JSP)

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>

Page 53: 19-Java Server Pages (JSP)

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);

Page 54: 19-Java Server Pages (JSP)

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

Page 55: 19-Java Server Pages (JSP)

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

Page 56: 19-Java Server Pages (JSP)

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

Page 57: 19-Java Server Pages (JSP)

Web Application Architectures-3

Servlet Centric Architecture

Page 58: 19-Java Server Pages (JSP)

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...

Page 59: 19-Java Server Pages (JSP)

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

Page 60: 19-Java Server Pages (JSP)

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.

Page 61: 19-Java Server Pages (JSP)

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?

Page 62: 19-Java Server Pages (JSP)

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.