chapter 7 java server pages
DESCRIPTION
Chapter 7 Java Server Pages. Objectives. Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP List and describe the JSP element types Explain the operation of a JSP error page Explain the operation of include and forward directives - PowerPoint PPT PresentationTRANSCRIPT
Chapter 7Java Server Pages
Objectives
• Explain how the separation of concerns principle applies to JSP
• Describe the operation and life-cycle of a JSP• List and describe the JSP element types• Explain the operation of a JSP error page• Explain the operation of include and forward
directives• Explain the purpose of a Java Bean and how
one can be used from a JSP• Explain the purpose of a taglib and how a tag
can be used from a JSP
Separation of Concerns
• A basic principle of software design:
Software modules should have distinct responsibilities as much as possible
input
calculation
data retrieval
output
Separation of ContentFrom Processing (1/2)
• A servlet generating an HTML document intermixes Java code and HTMLpublic void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException() { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<html><head><title>" + "Example HTML" + "</title></head><body>"; ... out.println("</html>"); out.close();}
Separation of ContentFrom Processing (2/2)
• Java Server Pages (JSP) allow static HTML content to be separated from dynamic content (created by Java code) within a document<%@ page %><html><head><title>Example Page</title></head><body><h1>Example Page</h1><% String name = req.getParameter("name");%><p>Hello, <%= name %></p>...</html>
JSP Elements
• JSP tags belong to one of five element typesDeclaration: declare variable or procedure
Expression: evaluate a Java expression
Scriptlet: execute a Java code segment
Directive: a JSP compiler command
Action Element:interacts with another
component
JSP Declaration
• A declaration can be used to initialize variables or define procedures for use later in the JSP
<%! Date today = new Date(); %>
<%! // return the difference between two integers public int diff(int a, int b) { return (a < b) ? (b - a) : (a – b);}
%>
JSP Expression
• A JSP expression is evaluated and then replaced by that value
<%! Date today = new Date(); %>
<p>Today is: <%= today.toString() %> </p>
Generated HTML:<p>Today is: Mon Jun 15 08:05:00 EST 2009 </p>
JSP Scriptlet
• A JSP scriptlet is a short section of Java code that is executed in-line
• Scriptlets have access to several pseudovariables:– out HTML output stream– session current HttpSession object– request HTTPRequest object– response HTTPResponse object
JSP Scriptlet
• This scriptlet displays the current date and time
<% // output the current date and time
Date today = new Date();
out.println("<p>Today is: " + date.toString()
+ " </p>";
%>
JSP Scriptlet
• The scriptlet checks to see if a Boolean session attributed named "login" exists
<% // check to see if the user is logged in boolean loggedIn = ((Boolean)
session.getAttribute("login")).booleanValue();if (loggedIn) {
out.println("<p>Please select an option</p>"; } else { out.println("<p>Please login</p>"; }%>
JSP Scriptlet
• The scriptlet maintains a "hit count"
<% // get or create hit count Integer hitCount = (Integer) session.getAttribute("hits"); if (hitCount == null) { hitCount = new Integer(0): }
// increment and save hit count hitCount = new Integer(hitCount.intValue() + 1); session.setAttribute("hits", hitCount);
// display hit count <p>Hit Count: <%= hitCount.intValue() %></p>%>
JSP Life-Cycle
• JSP's are actually executed as servlets
• The first time a JSP is requested, it is translated to a servlet and compiled
• Each subsequent request executes the same servlet
JSPServlettranslated
upon firstrequest
JSP Life-Cycle
JSP Directive
• The page directive appears at the top of each JSP and controls its execution
• The page directive also specifies imports
<%@ page import="java.util.Date, java.io.*" %>
JSP Errors
• Compilation errors and run-time exceptions are logged and then returned as an HTML response
???
JSP Error Page
• The proper way to handle errors is to declare an error page
• The error page is invoked whenever a JSP compilation or run-time error occurs
• The error page can display a standard error message
JSP Error Page
• JSP that might throw an error:<%@ page import="java.util.*" errorPage="stderror.jsp" %>
... possible errors ...
• stderror.jsp:<%@ page IsErrorPage="true" %>
<html><head><title>Error Page</title></head><body><p>That request cannot be completed at this time.</p><p>Please contact your system administrator.</p></body></html>
JSP Action Element
• JSP action elements control interactions with other JSP's, including– include: add the contents of another JSP– forward: send a request to another JSP for
handling
JSP Include
• A JSP include can be used to add standard content to a JSP, such as headers and footers
<%@ page %>
<jsp:include page="stdheader.jsp" />
...unique content of this JSP...
<jsp:include page="stdfooter.jsp" />
JSP Forward
• A JSP forward causes control to be transferred to a different JSP<%@ page %><% // verify that user is logged in Boolean loggedIn = (Boolean) session.getAttribute("login"); if (loggedIn == null || loggedIn.booleanValue() == false) {%> <jsp:forward page="login.jsp" /><% }%>
the scriptlet iscontinuedafter the directive,which is not a Java statement
Java Beans
• A Java Bean is a Java class that can be invoked from a JSP
• This allows complex processing required by a JSP to be separated from the JSP
• A JSP can instantiate an instance of a bean class and invoke its methods
Java Bean Example
• Java Beanpackage bean;public class AdderUtility { public int add(int a, int b) { return a + b; }}
• JSP<%@ page %><jsp:useBean id="adder" class="bean.AdderUtility"
scope="session" />
<% int a, b, sum; … int sum = adder.add(a, b);%>
Java Bean Uses
• Java Beans are typically used to encapsulate complex application logic, including calculations, database access, or network access
JSP Java BeanDatabase
Network
Application
JSP Taglibs
• A tag library allows programmers to create custom tags to invoke application functions with JSPs
• Each custom tag is associated with a Java class that is executed when the tag is evaluated
Taglib Example
• JSP code:
<tags:boxin border="green">
This code appears in a green box
</tags:boxin>
This code appears in a green box
tag body content
Taglib Example
• BoxInTag.javapublic class BoxInTag extends BodyTagSupport { private String border; public void setBorder(String border) { this.border = border; } public int doStartTag() throws JspTagException { return EVAL_BODY_BUFFERED; } public int doEndTag() throws JspTagException { JspWriter out = pageContext.getOut(); String content = bodyContent.getString(); try { out.println("<div style=\"border-style: solid; border-color: " + border + "\">" + content + "</div>" ); } catch (IOException ioe) { ioe.printStackTrace(); } return EVAL_PAGE; }}
returns the tag bodycontent, i.e., thetext between thetag opening andclosing
Tag Library Definition File (TLD)
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"><taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance“ xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <description>Show Standings Tag</description> <tag> <name>boxin</name> <tag-class>tags.BoxInTag</tag-class> <description> Draw a box around the content </description> <body-content>tagdependent</body-content> </tag> </taglib>
Review
• Java Server Pages
• JSP life-cycle
• JSP Elements
• JSP include and forward directives
• Java Beans with JSP
• JSP taglibs