Beruflich Dokumente
Kultur Dokumente
05/04/2007
05/04/2007
Revision History
?
?
?
05/04/2007
Sub-topics of JSP
Before I proceed, let me talk about which parts of JSP will be dealt
with in this two hour session.
05/04/2007
Sub-topics of JSP
?
?
?
?
JSP Basic
JavaBeans for JSP
Custom tags
JSP Standard Tag Library (JSTL)
The topic of JSP can be divided into 4 sub-topics: first, JSP basics, second,
how JavaBeans are used within a JSP page, and third custom tags, which
are special kind of Java components specifically geared for JSP
technology, and finally JSP standard tag library, which is a standard set of
custom tags every J2EE compliant app server has to support.
In this two hour session, we are going to deal with only the first two subtopics - JSP basics and JavaBeans for JSP.
And the latter two topics, custom tags and JSP standard tag library (JSTL)
will be dealt with either later in this course or in advanced J2EE course.
05/04/2007
Another important topic people talk about these days are Web application frameworks,
which are based JSP and Servlet technologies. And this slide shows the list of those
frameworks.
I am sure many of you have heard of MVC pattern or MVC architecture. It stands for
Model View Controller and deals with what would be the best architecture at web-tier
in terms of reusability of code, robustness of design and implementation,
maintainability of code, and so on. And the MVC design pattern basically sums up the
knowledge and best practice guidelines that people have learned so far.
Among the MVC design pattern, a so-called Model2 architecture is the one everybody
agrees is the framework that provides best code reusability, best maintenability. In
Model 2 architecture, a servlet functions as a controller or a dispatcher while JSP pages
are used for handing the View.
Now there are several actual frameworks that are based on Model 2 architecture. And
the most popular one people use is Apache Struts. And Java Server Faces is a Java
Initiative in this area.
Then there are other frameworks such as Echo or Tapastry.
Again, we will deal with these topics in a bit more detail in Advanced J2EE
programming course.
05/04/2007
Agenda
?
?
?
?
?
?
?
?
So this is the list of topics that I am going to talk about in this two hour
session. First, I will talk about where JSP fits in the big picture of J2EE
architecture. And I will give a quick introduction on how JSP works. And
we will talk about life-cycle of JSP pages.
Then I will spend some time talking about how you develop JSP-based
web application. Then I will talk about anatomy of JSP page, that is, what
things make up a JSP page. And then I will talk about how JavaBeans are
used within the JSP page. Finally, I will talk about how error handling can
be done with JSP pages.
05/04/2007
JSP in a
Big Picture of Java EE
8
OK, let's talk about where JSP fits in from a big picture perspective of
J2EE architecture.
05/04/2007
This picture describes what roles JSP and Servlet plays in J2EE
architecture. Servlet is a program that extends the functionality of a web
server by generating dynamic contents and interacting with web clients
using request-response paradigm.
JSP is an extensible web technology that uses template data, custom
elements, string languages, and server-side Java objects to return dynamic
contents to a client. Typically the template data or static data is HTML or
XML elements.
05/04/2007
Static contents
Dynamic contents
User identity
Time of the day
User entered values through forms and selections
Examples
?
10
I've been saying on and off that JSP and servlet technologies are for generating
and displaying dynamic contents (as opposed to static contents). Now for those
of you who are not familiar with servlet or JSP may wonder what I mean by static
contents and dynamic contents. So let me clarify these terms a bit before I move
on.
Static contents are basically HTML pages whose contents do not change
regardless of the external conditions. For example, our class website is in fact an
example of static contents. It does not contain any dynamically generated content
even a counter that counts how many people have accessed the page. In other
words, it displays the same information for everyone regardless who accesses the
page.
The dynamic contents, on the other hand, are dynamically generated based on
external conditions such as user identity or time of the day or values that are
entered by an end user through form-based input or choice selection the user has
made. Examples of dynamic contents are personally customized ETrade webpage
or Personal Yahoo webpage. Based on your identity, the web server dynamically
generate customized information, for example, your stock account balance or
stock transactions you performed and so on. And the web server uses
technologies such as servlet or JSP for generating these dynamic contents.
10
By the way, a typical web application uses both static and dynamic contents
together.
05/04/2007
11
This picture shows where JSP and Servlet based web components fit in a
multi-tier J2EE architecture. As you can see, the JSP and servlet are
running inside a Web container performing dynamic contents generation.
As for business logic processing, JSP and servlets could be invoking
services offered by EJB beans that are running in EJB container or they
might perform the business logic processing themselves.
11
05/04/2007
Dynamic content
Java code
Displaying properties of JavaBeans
Invoking business logic defined in Custom tags
12
12
05/04/2007
13
So this is an example of a very simple JSP page. Here the things that are
colored in blue are static contents while the things in red color are JSP
elements that performs dynamic content generation.
In this example, the current time and date is dynamically generated and
displayed, thus reflecting the current time and date, while the rest of the
page is static.
13
05/04/2007
Output
14
This is the display when you access the previous JSP page. So depending
on when you access the page, the time and date will be different while the
Hello World Message would remain the same.
Now in this page, the Hello, World greeting message is displayed in
English. But if you want to display the greeting message in local language
or display different greeting depending on the time of the day, for example,
Good morning during morning period or Good afternoon during the
afternoon period, then even that greeting has to be generated as dynamic
contents.
14
05/04/2007
JSP
Servlets
HTML code in
Java
? Not easy to
author
JSP
Java-like code in
HTML
? Very easy to
author
? Code is compiled
into a servlet
?
15
15
05/04/2007
JSP Benefits
?
?
?
?
16
16
05/04/2007
17
17
05/04/2007
18
05/04/2007
JSP
Architecture
19
19
05/04/2007
20
20
05/04/2007
Pure Servlet
if(bean.isOrderValid(..)){
bean. saveOrder(.);
forward(conf.jsp);
}
JSP
presentation
<html>
<body>
<ora: loop name =order>
..
< /ora :loop>
<body>
</html>
JavaBeans
isOrderValid( )
Business logic
saveOrder( )
21
21
05/04/2007
JSP Architecture
22
This picture shows JSP architecture. When a client sends a HTTP request
to a JSP page, the JSP page will be translated and compiled into a
corresponding servlet class. Or in many web containers, the JSP pages are
compiled into servlet classes when they are deployed. Once it is compiled
into a servlet class, then it follows the same life-cycle of a servlet.
22
05/04/2007
Life-Cycle of a JSP
Page
23
OK. Let's talk about the life cycle of a JSP page, that is, how a deployed JSP
page gets translated and compiled into a corresponding servlet and then how
the resulting servlet instance serves the client requests.
23
05/04/2007
24
05/04/2007
Translation phase
Compile phase
Execution phase
25
So the lifecycle of a JSP page can be divided into three phases: (1)
translation phase in which a JSP page gets translated into a servlet code,
(2) compilation phase in which servlet code gets compiled, (3) then
execution phase in which servlet instance then serves client request.
Usually translation and compilation phases occur together.
25
05/04/2007
Translation/Compilation Phase
?
?
?
<AppServer_HOME>/work/Standard
Engine/localhost/context_root/pageName$jsp.java
<AppServer_HOME>/work/Standard
Engine/localhost/date/index$jsp.java
26
26
05/04/2007
Translation/Compilation Phase
?
27
27
05/04/2007
28
Once the page has been translated and compiled, the JSP page's servlet for the
most part follows the servlet life cycle as following:
1. If an instance of the JSP page's servlet does not exist, the container Loads the
JSP page's servlet class
2. Container then creates an instance of the servlet class
3. Container then initializes the servlet instance by calling the jspInit method
4. Container invokes the _jspService() method, passing a request and response
object.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy()
method.
28
05/04/2007
29
You can customize the initialization process to allow the JSP page to
read persistent configuration data, initialize resources, and perform any
other one-time activities by overriding the jspInit() method of the
JspPage interface.
29
05/04/2007
30
30
05/04/2007
Example: initdestroy.jsp
<%@ page import="database.*" %>
<%@ page errorPage="errorpage.jsp" %>
<%-- Declare initialization and finalization methods using JSP declaration -%>
<%!
private BookDBAO bookDBAO;
public void jspInit() {
// retrieve database access object, which was set once per web
application
bookDBAO =
(BookDBAO)getServletContext().getAttribute("bookDB");
if (bookDBAO == null)
System.out.println("Couldn't get database.");
}
public void jspDestroy() {
bookDBAO = null;
}
%>
31
31
05/04/2007
Now let's go over the steps you will follow to develop JSP-based web
application.
32
05/04/2007
33
So this is the list of steps you will follow to develop and deploy a web application. By
the way, this is the same steps we talked during the WebApplication Architecture
session. I modified it a bit here so that the focus is given to JSP.
First, you will write and compile web component code, that is servlet Java code or JSP
pages and helper classes that are used by those web components. You also need to
create any static resources such as images or HTML pages.
Next, you will create deployment descriptor, that is, web.xml file. Then you will build
web application. As was mentioned, a web application can be either in the form of
WAR file or in the form of laid out directory structure of the WAR file.
Then you will install and deploy the web application to the web container. Once a web
application is deployed, then client can access the web resources through the HTML
browser. So let's go over each of these steps one by one.
33
05/04/2007
34
So the first step is to write and compile web component codes. Now just like any other
application development, you might want to create development directory structure that
fits your need. As we will see in the following slide, people recommend a particular
directory structure they found suitable for web application development. And different
servlet container technologies use a bit different directory structures. We are using
Tomcat's example here.
Once you create an appropriate development directory structure, you can then write
servlet Java code or JSP pages along with related helper classes and other pieces. Now
another thing people find quite useful is to use ANT build tool for the development and
deployment tasks of web applications. ANT is platform independent make utility. And
the file that contains the build instruction is called build.xml file.
34
05/04/2007
Root directory
35
To facilitate iterative development and keep Web application source separate from
compiled files, the source code for the tutorial examples is stored in the following
structure under each application directory, for example, hello1.
build.xml - Ant build file
context.xml - Optional application configuration file
? src directory - Java source of servlets and JavaBeans components
? web directory - JSP pages and HTML pages, images
?
?
The Ant build file (build.xml) distributed with the examples contain targets to create an
unpacked WAR structure in the build subdirectory of mywebapp, copy and compile
files into that directory, and invoke the manager commands via special Ant tasks to
install, reload, remove, deploy, and undeploy applications.
35
05/04/2007
web.xml
build.xml
(it does not have src directory since this does not
use any Java classes as utility classes)
36
So this is an example directory structure of hello1 web application you find in the Java
WSDP. There are two servlet Java source files. And there is a web directory called web
which contains WEB-INF directory and other static resource files.
36
05/04/2007
HTML pages
Custom pages
Login pages
Error pages
Example: duke.waving.gif
37
The next step is to create any static resources that will be used by the web components.
And they include some static HTML pages or image files. And an example of image is
duke that you see quite often in various Java-related web pages.
37
05/04/2007
3. Create deployment
descriptor (web.xml)
?
38
The next step is to create deployment descriptor, web.xml file. By the way, the name of
this file has to be web.xml file.
The web.xml file contains deployment time and runtime instructions to the web
container. For example, you can specify the URN that clients of your web applications
will use to access your web components. Every web application has to have a web.xml
file.
38
05/04/2007
For JSP web component, the sub element that needs to be specified under <servlet>
element is <jsp-file> instead of <servlet-class> element.
Now here in hello2 example, you can see that instead of specifying a servlet class with
<servlet-class> element, the web.xml file specifies the JSP file with <jsp-file>. For
example, the web.xml file of the Hello1 servlet, there is a following line
<servlet-class>GreetingServlet</servlet-class>
In web.xml for JSP page, we have the following line instead.
<jsp-file>/greeting.jsp</jsp-file>
39
05/04/2007
Once you have all the pieces, you can create a web application. As mentioned before, a
web application is basically a deployable package that contains everything that is
needed for the deployment.
A web application is either in the form of *.war file or unpacked or laid out form of the
*.war file. Typically the build process of the web application involves creating build
directory which is the root directory for the compile time generated pieces such as Java
classes and pieces that are needed to create *.war file such as web.xml file. For
example, the compiled java classes will end up residing in build/WEB-INF/classes
directory and web.xml file is also copied to build/WEB-INF directory and the image
files are copied into the build directory itself. Basically the build directory is the
reflection of directory structure that a particular web container expects.
40
05/04/2007
Hello2
web directory
build.xml
build directory
? WEB-INF directory
classes directory
web.xml
? duke.waving.gif
? greeting.jsp
? response.jsp
41
So this is the example directory structure of hello1 web application. Once the build
process is completed via ant build command, the build directory gets created if it is
not present yet, and greetingservlet and responseservlet classes are created in classes
subdirectory and web.xml file is copied from web directory to build/WEB-INF directory
and image file is copied from web directory to build/ directory. Now the build directory
is now ready to be taken either as a source directory for creating *.war file or can be
copied over to web container for deployment.
41
05/04/2007
ant install
ant deploy
Once you built a ready to deployable web application, you can now deploy the
application over the web container.
Now for Tomcat, there are two different ways you can install/deploy your web
applications. The first method is by sending a request to Tomcat manager and the other
method is a bit of brute force method which is you manually copy the *.war file or
directory structure to the webapps directory of Tomcat and then restart.
Now let's talk about a bit on the first method. Basically what is happening underneath
when you invoke ant install or ant deploy command is that you are running Java
application in which HTTP request message that contains the information about your
web application such as name and location of it gets constructed and sent to Tomcat
manager which itself is a servlet application.
42
05/04/2007
Manual Method
Copying *.war file or unpacked directory to <tomcatinstall>/webapps/ directory manually and then
restart Tomcat
43
Now when you are asking Tomcat manager to install or deploy your web application,
basically what you are asking is to change a setting on the server side which should be
privileged operations. What that means is that you need to provider proper credentials
along with your installation and deployment requests. This is why you need
build.properties file with proper user id and password. Otherwise, you will experience
HTTP 401 error condition, which basically says that an access controlled web resource,
in this case, the Tomcat manager, is being accessed with invalid userid and password.
Now let's talk about the difference between installation and deployment. Installation
under Tomcat's context is a temporary installation while deployment is a permanent
deployment. So when Tomcat gets restarted, an installed web application is not going
to be run again while a deployed application will be started automatically by the
container.
Again the manual method is basically coping the *.war file or whole directory structure
to Tomcat's webapps directory and in this method.
43
05/04/2007
http://localhost:8080/hello2/greeting
44
Once your web application is deployed, then you can try to access the web components
via your browser by specifying the appropriate URN address.
44
05/04/2007
http://localhost:8080/hello2/greeting
45
45
05/04/2007
response.jsp
46
This is response html page that gets displayed as a result of the handling of the first
HTTP request that comes from the client.
46
05/04/2007
Comparing
Hello1 Servlet &
Hello2 JSP code
47
Now let's compare Hello world programs written in Servlet and JSP and see
how they match up against each other.
47
05/04/2007
GreetingServlet.java (1)
import
import
import
import
import
java.io.*;
java.util.*;
java.sql.*;
javax.servlet.*;
javax.servlet.http.*;
/**
* This is a simple example of an HTTP Servlet. It responds to the GET
* method of the HTTP protocol.
*/
public class GreetingServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
response.setBufferSize(8192);
PrintWriter out = response.getWriter();
// then write the data of the response
out.println("<html>" +
"<head><title>Hello</title></head>");
48
So this is code listing of GreetingServlet in Hello1 example under Java WSDP. This is
the first part of 3 pages of the code.
What happens in this code is pretty simple. It basically receives a HTTP request, then
create output stream object and write HTTP response to the output stream.
48
05/04/2007
GreetingServlet.java (2)
// then write the data of the response
out.println("<body bgcolor=\"#ffffff\">" +
"<img src=\"duke.waving.gif\">" +
"<h2>Hello, my name is Duke. What's yours?</h2>" +
"<form method=\"get\">" +
"<input type=\"text\" name=\"username\" size=\"25\">" +
"<p></p>" +
"<input type=\"submit\" value=\"Submit\">" +
"<input type=\"reset\" value=\"Reset\">" +
"</form>");
String username = request.getParameter("username");
// dispatch to another web resource
if ( username != null && username.length() > 0 ) {
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/response");
if (dispatcher != null)
dispatcher.include(request, response);
}
out.println("</body></html>");
out.close();
}
49
This is the continuation of writing to the output stream. Then it dispatches to another
web resource called /response.
49
05/04/2007
GreetingServlet.java (3)
public String getServletInfo() {
return "The Hello servlet says hello.";
}
}
50
50
05/04/2007
greeting.jsp
<html>
<head><title>Hello</title></head>
<body bgcolor="white">
<img src="duke.waving.gif">
<h2>My name is Duke. What is yours?</h2>
<form method="get">
<input type="text" name="username" size="25">
<p></p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<%
String username = request.getParameter("username");
if ( username != null && username.length() > 0 ) {
%>
<%@include file="response.jsp" %>
<%
}
%>
</body>
</html>
51
Now this is the Hello web application this time using JSP. As you can see, JSP includes
HTML tags so you are not creating HTML response in your Java code, instead they are
part of JSP page. Then some dynamic contents are created through embedded Java
code within the JSP page.
By the way, as we will see later on, inserting Java code as part of JSP page is not really
a recommended way of performing dynamic contents generation. I am just showing this
example to make a point.
51
05/04/2007
ResponseServlet.java
import
import
import
import
import
java.io.*;
java.util.*;
java.sql.*;
javax.servlet.*;
javax.servlet.http.*;
52
This is the web component, ResponseServlet, that was dispatched from the
GreetingServlet.
52
05/04/2007
response.jsp
<h2><font color="black">Hello, <%=username%>!</font></h2>
53
This the corresponding JSP page. As you can see, as far as displaying is concerned, JSP
is a much simpler to use.
53
05/04/2007
JSP is Servlet!
54
Now I want you to understand that JSP and servlet are very closely related. I
would even claim that JSP pages are servlets. What happens underneath is that
JSP pages are translated and compiled into corresponding servlet code and
classes transparently.
In a sense, JSP provides separation of contents generation from presentation
logic while maintaining all the benefits that come with servlet.
54
05/04/2007
JSP is Servlet
?
55
Just to reiterate how JSP and Servlet are closely related, I would say that JSP is in fact
Servlet.
First JSP pages get translated into servlet class when they get deployed. Second, the
scriptlet which is Java code within JSP page ends up being directly inserted into the
jspService() method of the resulting servlet class without any modification. Third, the
implicit objects that are available to servlet programmers such as HttpSession object,
ServletContext objects are also available to JSP page designers, JavaBeans developers,
custom tag designers.
55
05/04/2007
greeting$jsp.java (1)
package org.apache.jsp;
import
import
import
import
javax.servlet.*;
javax.servlet.http.*;
javax.servlet.jsp.*;
org.apache.jasper.runtime.*;
static {
}
public greeting$jsp( ) {
}
private static boolean _jspx_inited = false;
public final void _jspx_init() throws
org.apache.jasper.runtime.JspException {
}
56
So this is the greeting.jsp's corresponding servlet class that was created by the
container.
56
05/04/2007
greeting$jsp.java (2)
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;
String _value = null;
57
This is continuation of translated code. Please note that there are variables that contain
the references to servlet related objects such as pageContext object, HttpSession object,
ServletContext object, ServletConfig object and output stream object.
57
05/04/2007
greeting$jsp.java (3)
try {
if (_jspx_inited == false) {
synchronized (this) {
if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request,
response,"", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
58
58
05/04/2007
greeting$jsp.java (4)
// HTML // begin [file="/greeting.jsp";from=(38,4);to=(53,0)]
out.write("\n\n<html>\n<head><title>Hello</title></head>\n<body
bgcolor=\"white\">\n<img src=\"duke.waving.gif\"> \n<h2>My name is Duke.
What is yours?</h2>\n\n<form method=\"get\">\n<input type=\"text\"
name=\"username\" size=\"25\">\n<p></p>\n<input type=\"submit\"
value=\"Submit\">\n<input type=\"reset\"
value=\"Reset\">\n</form>\n\n");
// end
// begin [file="/greeting.jsp";from=(53,2);to=(56,0)]
String username = request.getParameter("username");
if ( username != null && username.length() > 0 ) {
// end
// HTML // begin [file="/greeting.jsp";from=(56,2);to=(57,4)]
out.write("\n
");
// end
// HTML // begin [file="/response.jsp";from=(38,4);to=(40,31)]
out.write("\n\n<h2><font color=\"black\">Hello, ");
// end
// begin [file="/response.jsp";from=(40,34);to=(40,42)]
out.print(username);
59
59
05/04/2007
greeting$jsp.java (5)
// HTML // begin [file="/response.jsp";from=(40,44);to=(55,0)]
out.write("!</font></h2>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
// end
// HTML // begin [file="/greeting.jsp";from=(57,37);to=(58,0)]
out.write("\n");
// end
// begin [file="/greeting.jsp";from=(58,2);to=(60,0)]
}
// end
// HTML // begin [file="/greeting.jsp";from=(60,2);to=(63,0)]
out.write("\n</body>\n</html>\n");
// end
} catch (Throwable t) {
if (out != null && out.getBufferSize() != 0) out.clearBuffer();
if (pageContext != null) pageContext.handlePageException(t);
} finally {
if (_jspxFactory != null)
_jspxFactory.releasePageContext(pageContext);
}
}
}
60
This is the continuation of code that deals with generation of HTML page. As you can
see, all the dirty work of generating HTML page is done by the compiler.
60
05/04/2007
Dynamic Content
Generation
Techniques
in JSP
61
OK, by now I hope you got the sense on what the dynamic contents is and how
it is generated. Now let's talk about the dynamic contents generation
techniques in a bit more detail.
61
05/04/2007
62
62
05/04/2007
This slide lists dynamic contents generation techniques that can be used with
JSP in the order of its sophistication, from the least sophisticated to the most
sophisticated. So let's talk about these in a bit more detail.
63
05/04/2007
hard to maintain
hard to reuse code
hard to understand for web page authors
64
The least sophisticated method is to place all the Java code within a
JSP page. Because, in this method, the business logic which is
represented in Java code and presentation logic which is represented
in JSP pages are intermixed, it provides somewhat weak separation
between the two, which means it is rather hard to maintain and reuse
the code. And web page authors will have difficult time to
understand the JSP page. So this design model provides only a
slightly better separation between contents and presentation logic
than servlet only code.
64
05/04/2007
65
65
05/04/2007
?
?
Now in the next level, you can develop those utility classes in the
form of simple component, JavaBeans in this case.
Using JavaBeans within a JSP page has an advantage over method
(a) and (b) because there is a built-in support of getting and setting
JavaBeans properties in JSP architecture as we will see later on.
And because of this built-in support, accessing JavaBeans from JSP
page is a lot easier thing to do for web page authors again compared
to method (a) and (b).
And because the logic of contents generations is captured in a
component form of JavaBeans, the reusability and maintenability
increases.
66
05/04/2007
?
?
67
05/04/2007
Apache Struts
68
68
05/04/2007
69
69
05/04/2007
Apache Struts
JavaServer Faces (JSF)
Other frameworks: Echo, Tapestry, WebWorks,
Wicket
70
70
05/04/2007
Now let's talk about how to use Java code within JSP page using JSP scripting
elements. Using JSP scripting elements addresses the dynamic contents
generation techniques (a) and (b).
71
05/04/2007
72
Scripting elements let you insert raw Java code into the JSP page directly
and this code will be in turn inserted into the Servlet code that will be
generated from the JSP page.
As was mentioned, the best practice recommendation is not to use scripting
elements if possible.
Scripting elements can be in 3 different forms - expression, scriptlets, and
declarations and they use different syntax as shown in the slide.
72
05/04/2007
Expressions
?
Format
<%= Expression %> or
<jsp:expression>Expression</jsp:expression>
Semi-colons are not allowed for expressions
73
73
05/04/2007
Example: Expressions
?
These are the examples of expressions. For example, you can use
expression to display current time using Java Date class. Or you can
display the random number using Math class.
Or as was mentioned, you can access all implicit objects such as
HttpServletRequest, ServletContext object, and HttpSession objects.
Because JSP already defined the names of these implicit objects, you
have to use predefined names in your JSP page. For example
HttpServletRequest object is represented by request, ServletContext
object by application, HttpSession object by session.
74
05/04/2007
Scriptlets
?
75
A JSP scriptlet is used to contain any code fragment that is valid for the
scripting language used in a page. The syntax for a scriptlet is as follows:
<%
scripting language statements
%>
When the scripting language is set to Java programming language, a
scriptlet is transformed into a Java programming language statement
fragment and is inserted into the service() method of the JSP page's servlet.
A programming language variable created within a scriptlet is accessible
from anywhere within the JSP page.
75
05/04/2007
Example: Scriptlets
?
76
This is an example scriptlets. The first example fills the output stream
with some query data while in the 2 nd example, response type is set
through HttpServletResponse implicit object.
76
05/04/2007
77
77
05/04/2007
78
78
05/04/2007
79
Now I know we dealt with several JSP elements. And let's see these
different JSP elements are in fact translated into corresponding Java
code.
Now let's say that we have the JSP page fragment that contains 3
different JSP elements mentioned in this slide. And let's see how these 3
JSP elements are translated into Java code in the following slide.
79
05/04/2007
80
80
05/04/2007
Declarations
?
?
?
81
81
05/04/2007
82
82
05/04/2007
83
And this is the resulting Servlet code. Please note that method declaration
reside outside of _jspService() method. And usage of the declared method
within in expression inside the _jspService() method.
83
05/04/2007
Example: Declaration
<%!
private BookDBAO bookDBAO;
public void jspInit() {
...
}
public void jspDestroy() {
...
}
%>
84
This slide shows how you can override jspInit() and jspDestroy() using
declaration.
84
05/04/2007
<jsp:expression>Expression</jsp:expression>
<jsp:scriptlet> Java code</jsp:scriptlet>
<jsp:declaration> declaration code
</jsp:declaration>
Now as shown several times, there are two different syntax or format for
JSP elements, one that is being supported from JSP 1.1 and the other,
which is compliant with XML syntax, is supported from JSP 1.2.
Using XML syntax for JSP element has several advantages. For
example, you can use XML validation and many XML tools out there.
85
05/04/2007
Including and
Forwarding to Other
Web Resource
86
86
05/04/2007
include directive
jsp:include element
87
There are two mechanisms for including another Web resource in a JSP
page: the include directive and the jsp:include element.
87
05/04/2007
Include Directive
?
88
The include directive is processed when the JSP page is translated into a
servlet class. The effect of the directive is to insert the text contained in
another file-- either static content or another JSP page--in the including
JSP page. You would probably use the include directive to include
banner content, copyright information, or any chunk of content that you
might want to reuse in another page. The syntax for the include directive
is as follows:
<%@ include file="filename" %>
For example, all the bookstore application pages include the file
banner.jsp which contains the banner content, with the following
directive:
<%@ include file="banner.jsp" %>
88
05/04/2007
jsp:include Element
?
?
89
05/04/2007
90
So when do you want use Include directive and when do you want to use
include element.
The best practice guideline recommends that you use include directive if
the included JSP page changes rarely because directive processing is
faster than the processing of include element.
And use include element when the contents changes often or if the page
to include cannot be decided until the main page is requested.
90
05/04/2007
91
05/04/2007
Directives
92
92
05/04/2007
Directives
?
93
OK, let's talk about directive. Directives are messages (or instruction) to
the JSP container. And directives do not produce any output. And the
syntax is as shown in the slide.
93
05/04/2007
There are three types of directives. page directive, include directive, and
TagLib directive. The page directive is used to communicate page
dependent attributes to the JSP container for example importing Java
classes.
The include directive is used to include text or code at JSP translation time,
for example including a HTML page.
The TagLib directive indicates a tag library that the JSP container should
interpret.
94
05/04/2007
Page Directives
?
95
This slide shows the examples of page directives. For example, you can
use directory to specify which Java classes should be imported, what mime
types should be generated, how multithreading is handled, and which page
handles errors and so on.
95
05/04/2007
Implicit Objects
?
?
?
96
96
05/04/2007
Implicit Objects
?
?
?
?
?
?
?
request (HttpServletRequest)
response (HttpServletRepsonse)
session (HttpSession)
application(ServletContext)
out (of type JspWriter)
config (ServletConfig)
pageContext
97
97
05/04/2007
Scope Objects
98
98
05/04/2007
Different Scope
99
The scope objects that are defined under servlet are also available to JSP
page designers, bean developers, custom tag developers. Scope objects are
used to maintain object-value pairs that can be shared within a particular
scope.
There are four scope objects whose scope are different. On the top, we
have application scope object, whose scope is web application. A single
web application can be made of multiple web components, that is, multiple
servlets and JSP pages. And any object-value pairs that are maintained in
application scope are shared among the servlets and JSP within that
application.
Session scope object maintains object-value pairs that can be shared within
the session.
99
05/04/2007
server
Session 1
Session ID 1
Client 2
Session ID 2
Session 2
Client 1
server
application
Client 2
100
100
05/04/2007
request
Page 1
forward
Page scope
response
request
Page 2
Page 3
Page scope
response
Page scope
request scope
Page 4
forward
Page scope
request scope
Session scope
101
101
05/04/2007
JavaBeans Components
for JSP
102
Now let's talk about how JavaBeans components can be used within JSP
page.
102
05/04/2007
103
JavaBeans components are Java classes that can be easily reused and
composed together into applications.
Any Java class that follows certain design conventions can be a
JavaBeans component. JavaBeans component design conventions
govern the properties of the class and govern the public methods that
give access to the properties.
JavaServer Pages technology directly supports using JavaBeans
components with JSP language elements. You can easily create and
initialize beans and get and set the values of their properties
And JavaBeans can contain business logic or database access logic.
103
05/04/2007
A property can be
104
05/04/2007
Example: JavaBeans
public class Currency {
private Locale locale;
private double amount;
public Currency() {
locale = null;
amount = 0.0;
}
public void setLocale(Locale l) {
locale = l;
}
public void setAmount(double a) {
amount = a;
}
public String getFormat() {
NumberFormat nf =
NumberFormat.getCurrencyInstance(locale);
return nf.format(amount);
}
}
105
105
05/04/2007
106
05/04/2007
107
05/04/2007
108
Now compare the two JSP codes. As you can tell JavaBeans based
JSP code is a lot more simpler and easy to understand and would be
easier to maintain. In other words, for web page authors, using
JavaBeans syntax is a lot easier than writing Java code.
108
05/04/2007
?
?
So just to summarize why you want to use JavaBeans over pure Java
code, there are several reasons.
First, page authors do not have to know Java programming language
in order to use JavaBeans in JSP page because usage syntax of
JavaBeans is very simple. Because content generation or business
logic is captured in the form of JavaBeans component, it provides a
stronger separation between content and presentation. And a single
JavaBean can be in fact reusable in other JSP pages.
JavaBeans also make it easier to share objects among multiple JSP
pages or between requests.
Finally JavaBeans greatly simplify the process of reading request
parameters, converting from strings, and stuffing the resuts inside
objects.
109
05/04/2007
Creating a JavaBeans
?
You can declare that your JSP page will use a JavaBeans component
using either one of the two formats mentioned above. The second
format is used when you want to include jsp:setProperty statements for
initializing bean properties. So the 2 nd format is used only when a new
bean instance has to be created. If the bean instance already is present
as an attribute in the scope object, no setting occurs.
The jsp:useBean element declares that the page will use a bean that is
stored within and accessible from the specified scope, which can be
application, session, request, or page. If no such bean exists, the
statement creates the bean and stores it as an attribute of the scope
object.
The value of the id attribute determines the name of the bean in the
scope and the identifier used to reference the bean in other JSP elements
and scriptlets.
110
05/04/2007
Via JSP:setProperty
<jsp:setProperty name="beanName"
property="propName" value="string constant"/>
beanName must be the same as that specified for
the id attribute in a useBean element
There must be a setPropName method in the bean
111
There are two ways to set JavaBeans component properties in a JSP page:
with the jsp:setProperty element or with a scriptlet
<% beanName.setPropName(value); %>
Here beanName must be the same as that specified for the id attribute in a
useBean element. There must be a setPropName method in the JavaBeans
component. And paramName must be a request parameter name.
The syntax of the jsp:setProperty element depends on the source of the
property value. <jsp:setProperty name="beanName"
property="propName" value="string constant"/> is used when the source
is string constant. <jsp:setProperty name="beanName"
property="propName" param="paramName"/> is used when the source
is Request parameter.
111
05/04/2007
<jsp:setProperty name="beanName"
property="propName" value="string constant"/>
<jsp:setProperty name="beanName"
property="propName" param="paramName"/>
<jsp:setProperty name="beanName"
property="propName"/>
<jsp:setProperty name="beanName" property="*"/>
<jsp:setProperty name="beanName"
property="propName" value="<%= expression
%>"/>
112
112
05/04/2007
113
05/04/2007
114
114
05/04/2007
115
There are two ways to get JavaBeans component properties in a JSP page:
with the jsp:setProperty element or with a scriptlet
115
05/04/2007
2 ways
via scriptlet
?
via JSP:setProperty
?
Requirements
116
05/04/2007
Example
<%
// Print a summary of the shopping cart
int num = cart.getNumberOfItems();
if (num > 0) {
%>
117
117
05/04/2007
118
The above picture summarizes where various types of objects are stored
and how those objects can be accessed from a JSP page.
Objects created by the jsp:useBean tag are stored as attributes of the scope
objects and can be accessed by jsp:[get|set]Property tags and in scriptlets
and expressions.
Objects created in declarations and scriptlets are stored as variables of the
JSP page's servlet class and can be accessed in scriptlets and expressions.
118
05/04/2007
Error Handling
119
119
05/04/2007
In
120
120
05/04/2007
Example: initdestroy.jsp
<%@ page import="database.*" %>
<%@ page errorPage="errorpage.jsp" %>
<%!
private BookDBAO bookDBAO;
public void jspInit() {
// retrieve database access object, which was set once per web
application
bookDBAO =
(BookDBAO)getServletContext().getAttribute("bookDB");
if (bookDBAO == null)
System.out.println("Couldn't get database.");
121
This example code shows how to add error handling page as a page
directive.
121
05/04/2007
Example: errorpage.jsp
<%@ page isErrorPage="true" %>
<%@ page import="java.util.*" %>
<%
ResourceBundle messages =
(ResourceBundle)session.getAttribute("messages");
if (messages == null) {
Locale locale=null;
String language = request.getParameter("language");
if (language != null) {
if (language.equals("English")) {
locale=new Locale("en", "");
} else {
locale=new Locale("es", "");
}
} else
locale=new Locale("en", "");
messages = ResourceBundle.getBundle("BookStoreMessages", locale);
session.setAttribute("messages", messages);
}
%> ...
122
122
05/04/2007
Example: errorpage.jsp
... (continued)
<html>
<head>
<title><%=messages.getString("ServerError")%></title>
</head>
<body bgcolor="white">
<h3>
<%=messages.getString("ServerError")%>
</h3>
<p>
<%= exception.getMessage() %>
</body>
</html>
123
(to be added)
123
05/04/2007
Date Example
124
124
05/04/2007
125
The Web page above is a form that allows you to select a locale and
displays the date in a manner appropriate to the locale.
125
05/04/2007
Date Example
<%@ page import="java.util.*" %>
<%@ page import="MyLocales" %>
<%@ page contentType="text/html; charset=ISO-8859-5" %>
<html>
<head><title>Localized Dates</title></head>
<body bgcolor="white">
<jsp:useBean id="locales" scope="application" class="MyLocales"/>
<form name="localeForm" action="index.jsp" method="post">
<b>Locale:</b>
126
126
05/04/2007
Date Example
<select name=locale>
<%
Iterator i = locales.getLocaleNames().iterator();
String selectedLocale = request.getParameter("locale");
while (i.hasNext()) {
String locale = (String)i.next();
if (selectedLocale != null && selectedLocale.equals(locale) )
{ %>
<option selected><%=locale%></option>
<%
} else { %>
<option><%=locale%></option>
<%
}
}
%>
</select>
<input type="submit" name="Submit" value="Get Date">
</form>
127
Scriptlets (<% ... %> ) retrieve the value of the locale request parameter,
iterate over a collection of locale names, and conditionally insert HTML
text into the output.
Expressions (<%= ... %>) insert the value of the locale name into the
response.
127
05/04/2007
Date Example
<p>
<jsp:include page="date.jsp" flush="true" />
</body>
</html>
128
128
05/04/2007
Passion!
129
129