JSP Framework Use regular HTML for most of page Mark servlet code with special tags Entire JSP page gets translated into a servlet once, and servlet is what actually gets invoked f
Trang 1Web Programming with Java
Java Server Pages
Huynh Huu Viet
University of Information Technology Department of Information Systems
Email: viethh@uit.edu.vn
Trang 2Controller (MVC) Architecture
Trang 3The Need for JSP
With servlets, it is easy to
Read form data
Read HTTP request headers
Set HTTP status codes and response headers
Use cookies and session tracking
Share data among servlets
Remember data between requests
Get fun, high-paying jobs
But, it sure is a pain to
Use those println statements to generate HTML
Maintain that HTML
Trang 4JSP Framework
Use regular HTML for most of page
Mark servlet code with special tags
Entire JSP page gets translated into a servlet (once), and servlet
is what actually gets invoked (for each request)
Trang 5Benefits of JSP
Although JSP technically can't do anything servlets can't do, JSP makes it easier to:
Write HTML
Read and maintain the HTML
JSP makes it possible to:
Use standard HTML tools such as Macromedia
DreamWeaver or Adobe GoLive
Have different members of your team do the HTML layout than do the Java programming
JSP encourages you to
Separate the (Java) code that creates the content
from the (HTML) code that presents it
Trang 6Advantages of JSP Over Competing Technologies (1)
Versus ASP or ColdFusion
Better language for dynamic part
Portable to multiple servers and operating systems
Versus PHP
Better language for dynamic part
Better tool support
Versus pure servlets
More convenient to create HTML
Can use standard tools (e.g., DreamWeaver)
Divide and conquer
JSP programmers still need to know servlet
programming
Trang 7Advantages of JSP Over Competing Technologies (2)
Versus client-side JavaScript (in browser)
Capabilities mostly do not overlap with JSP, but
• You control server, not client
Trang 8<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="keywords" CONTENT="JSP,expressions,JavaServer Pages">
<META NAME="description“ CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET HREF="JSP-Styles.css“ TYPE="text/css">
<LI>Session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>
Trang 9JSP Lifecycle
Trang 10JSP/Servlets in the Real World
Web sites [1]
1) Google
• Custom technology,some Java
Trang 11Some webpages using JSP
Trang 12Controller (MVC) Architecture
Trang 13framework like Struts or JSF
Simple
Application
Complex
Application
Trang 14Design Strategy: Limit Java code in JSP Pages
You have two options
Put 25 lines of Java code directly in the JSP page
Put those 25 lines in a separate Java class and put 1 line in the JSP page that invokes it
Why is the second option much better?
Development You write the separate class in a
Javaenvironment (editor or IDE), not an HTML
environment
Debugging If you have syntax errors, you see
themimmediately at compile time Simple print
statements can be seen
Testing You can write a test routine with a loop that
does 10,000 tests and reapply it after each change
Reuse You can use the same class from multiple
pages
Trang 17JSP Expressions
<% =Java Expression %>
Expression evaluated, converted to String, and placed into
HTML page at the place it occurred in JSP page
That is, expression placed in _jspService inside out.print
Current time: <%= new java.util.Date() %>
Your hostname: <%= request.getRemoteHost() %>
<jsp:expression> Java Expression </jsp:expression>
You cannot mix versions within a single page You must page
use XML for entire page if you use jsp:expression.
• See slides at end of this lecture
Trang 18JSP/Servlet Correspondence
<H1>A Random Number</H1>
<%= Math.random() %>
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("<H1>A Random Number</H1>");
out.println(Math.random());
}
Trang 19 The Writer (a buffered version of type JspWriter) used
to send output to the client
Trang 21String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
Trang 22public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("<H2>foo</H2>");
out.println(bar());
baz();
Trang 23
JSP Scriptlets Example
customize the background color of a page
<BODY BGCOLOR=
"<%= request.getParameter("bgColor") %>">
Trang 25Make Parts of the JSP File Conditional
Scriplets are inserted into servlet exactly as written
Need not be complete Java expressions
Complete expressions are usually clearer and easier to maintain, however
Trang 26JSP Declarations
Format
<%!Java Code %>
Result
Code is inserted verbatim into servlet's class
definition, outside of any existing methods
Examples
<%! private int someField = 5; %>
<%! private void someMethod( ) { } %>
Design consideration
Fields are clearly useful For methods, it is usually
better to define the method in a separate Java class
XML-compatible syntax
<jsp:declaration> Java Code</jsp:declaration>
Trang 28JSP/Servlet Correspondence (2)
public class xxxx implements HttpJspPage {
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");
}
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
Trang 29<%! private int accessCount = 0; %>
<H2>Accesses to page since server reboot:
<%= ++accessCount %></H2>
</BODY></HTML>
Trang 30jspInit and jspDestroy Methods (1)
JSP pages, like regular servlets, sometimes want to use init and destroy
Problem: the servlet that gets built from the JSP page might already use init and destroy
Overriding them would cause problems
Thus, it is illegal to use JSP declarations to declare init or destroy
Solution: use jspInit and jspDestroy.
The auto-generated servlet is guaranteed to call
these methods from init and destroy, but the standard versions of jspInit and jspDestroy are empty
(placeholders for you to override)
Trang 31jspInit and jspDestroy Methods (2)
out.println("The number is " + num + "<br>");
out.println("The counter is " + count + "<br>");
%>
</body>
</html>
Trang 32Predefined Variables
The predefined variables (request, response, out, session, etc.)
are local to the _jspService method Thus, they are not available
to methods defined by JSP declarations or to methods in helper classes What can you do about this?
And they are usually preferred over JSP declarations
Trang 33When to use Expressions, Scriptlets or Declarations
Output a bulleted list of five random ints from 1 to 10.
Since the structure of this page is fixed and we use a separate helper class for the randomInt method,
JSP expressions are all that is needed.
Generate a list of between 1 and 10 entries (selected at
random), each of which is a number between 1 and 10.
Because the number of entries in the list is dynamic, a
Trang 34 RanUtilities Class
/** Simple utility to generate random integers */ public class RanUtilities {
/** A random int from 1 to range (inclusive) */
public static int randomInt(int range) {
return(1 + ((int)(Math.random() * range))); }
public static void main(String[] args) { int range = 10;
Trang 36%>
</UL>
</BODY></HTML>
Trang 39JSP Pages with XML Syntax
Why Two Versions
Classic syntax is not XML-compatible
• <%= %>, <% %>, <%! %> are illegal in XML
• HTML 4 is not XML compatible either
• So, you cannot use XML editors like XML Spy
You might use JSP in XML environments
• To build xhtml pages
• To build regular XML documents
– You can use classic syntax to build XML documents, but it is sometimes easier if you are working in XML to start with
» For Web services
» For Ajax applications
So, there is a second syntax
Trang 40Sample HTML 4 Page: Classic Syntax (sample.jsp)
Trang 41Sample XHTML Page: XML Syntax (sample.jspx)
Trang 42Controller (MVC) Architecture
Trang 43Purpose of the page Directive
servlet that will result from the JSP
page
If the servlet participates in sessions
Trang 44The import Attribute
Although JSP pages can be almost anywhere on
server, classes used by JSP pages must be in normal servlet dirs
Trang 45The Importance of Using Packages
What package will the system think that SomeHelperClass and SomeUtilityClass are in?
public class SomeClass {
public String someMethod( ) {
SomeHelperClass test = new SomeHelperClass( );
String someString = SomeUtilityClass.someStaticMethod( );
Trang 46The contentType and pageEncoding Attributes
Attribute value cannot be computed at request time
See section on response headers for table of the
most common MIME types
Trang 47Example: Conditionally Generating Excel Spreadsheets
You cannot use the contentType attribute
for this task, since you cannot make
Trang 48Example: Conditionally Generating Excel Spreadsheets
<BODY>
<CENTER>
<H2>Comparing Apples and Oranges</H2>
<%
String format = request.getParameter("format");
if ((format != null) && (format.equals("excel"))) { response.setContentType("application/vnd.ms-excel"); }
Trang 49The session Attribute
By default, it is part of a session
Saves memory on server if you have a high-traffic site
All related pages have to do this for it to be useful
Trang 50The buffer Attribute
Servers are allowed to use a larger size than you ask for, but not a smaller size
Default is system-specific, but must be at least 8kb
Trang 51The errorPage Attribute
Format
<%@ page errorPage="Relative URL" %>
Purpose
Specifies a JSP page that should process any
exceptions thrown but not caught in the current page
Notes
The exception thrown will be automatically available
to the designated error page by means of the
"exception“ variable
The web.xml file lets you specify application-wide
error pages that apply whenever certain exceptions or certain HTTP status codes result
• The errorPage attribute is for page-specific error pages
Example: ComputeSpeed.jsp
Trang 52The extends Attribute
Use with extreme caution
Can prevent system from using high-performance
custom superclasses
Typical purpose is to let you extend classes that
come from the server vendor (e.g., to support
personalization features), not to extend your own
classes
Trang 53The isThreadSafe Attribute
A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads
To tell the system when your code is not threadsafe,
so that the system can prevent concurrent access
• Normally tells the servlet to implement SingleThreadModel
Notes
Avoid this like the plague
• Causes degraded performance in some situations
• Causes incorrect results in others
Trang 54Non-Threadsafe Example Code (1)
<%! private int idNum = 0; %>
Trang 55Non-Threadsafe Example Code (2)
Is isThreadSafe Needed Here?
No! It is not needed Synchronize normally:
<%! private int idNum = 0; %>
Trang 56Controller (MVC) Architecture
Trang 57jsp:include:Including Pages at Request Time
Format
<jsp:include page="Relative address" />
Purpose
To reuse JSP, HTML, or plain text content
To permit updates to the included content without
changing the main JSP page(s)
Notes
JSP content cannot affect main page: only outputof
included JSP page is used
Don’t forget that trailing slash
Relative URLs that starts with slashes are
interpreted relative to the Web app, not
relative to the server root.
You are permitted to include files from INF
Trang 58it has only the tags appropriate to the place that it
will be inserted
Trang 59jsp:param: Augmenting Request Parameters
Trang 60<%@ include %>:Including Files at Page Translation Time
Format
<%@ include file="Relative address" %>
Purpose
To reuse JSP content in multiple pages, where JSP
content affects main page
Notes
Servers are not required to detect changes to the
included file, and in practice they don’t
Thus, you need to change the JSP files whenever the included file changes
You can use OS-specific mechanisms such as the
Unix “touch” command, or
• <% Navbar.jsp modified 10/ %>
Trang 61jsp:include vs <%@ include …>
Trang 62Which Should We Use?
Use jsp:include whenever possible
Changes to included page do not require any manual updates
Speed difference between jsp:include and the include directive (@include) is insignificant
The include directive (<%@ include …%>) has
additional power, however
Trang 63Understanding jsp:include vs <%@ include … %>
(instance variable)
would have to use @include
not use accessCount
Trang 64Controller (MVC) Architecture
Trang 65Uses of JSP Constructs
code directly
code indirectly (by means of utility classes)
Beans
framework like Struts or JSF
Simple
Application
Complex
Application
Trang 66What Are Beans?
Java classes that follow certain conventions
Must have a zero-argument (empty) constructor
• You can satisfy this requirement either by explicitly defining such a constructor or by omitting all constructors
Should have no public instance variables (fields)
• I hope you already follow this practice and use accessor methods instead of allowing direct access to fields
Persistent values should be accessed through
methods called getXxx and setXxx
• If class has method getTitle that returns a String, class is said
to have a String property named title
• Boolean properties use isXxx instead of getXxx
For more on beans, see
• http://java.sun.com/beans/docs/
Trang 67Why Use Beans?
• Can manipulate Java objects using only compatible syntax: no parentheses, semicolons, or curly braces
XML-• Promote a stronger separation between the content and the presentation
parameters and object properties
Trang 68Why You Should Use Accessors, Not Public Fields (1)
To be a bean, you cannot have public fields
So, you should replace
public double speed;
private double speed;
public double getSpeed() {
Trang 69Why You Should Use Accessors, Not Public Fields (2)
You can put constraints on values
public void setSpeed(double newSpeed) {
If users of your class accessed the fields
directly, then they would each be
responsible for checking constraints.
Trang 70Why You Should Use Accessors, Not Public Fields (3)
You can change your internal representation without changing interface
// Now using metric units (kph, not mph)
public void setSpeed(double newSpeed)
Trang 71Why You Should Use Accessors, Not Public Fields (4)
public double setSpeed(double newSpeed) {speed = newSpeed;
updateSpeedometerDisplay();
}
fields directly, then they would each
be responsible for executing side
effects
having display inconsistent from
actual values.