chapter 7 java server pages

29
Chapter 7 Java Server Pages

Upload: woody

Post on 21-Jan-2016

36 views

Category:

Documents


0 download

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 Presentation

TRANSCRIPT

Page 1: Chapter 7 Java Server Pages

Chapter 7Java Server Pages

Page 2: 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• 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

Page 3: Chapter 7 Java Server Pages

Separation of Concerns

• A basic principle of software design:

Software modules should have distinct responsibilities as much as possible

input

calculation

data retrieval

output

Page 4: Chapter 7 Java Server Pages

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

Page 5: Chapter 7 Java Server Pages

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>

Page 6: Chapter 7 Java Server Pages

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

Page 7: Chapter 7 Java Server Pages

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

%>

Page 8: Chapter 7 Java Server Pages

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>

Page 9: Chapter 7 Java Server Pages

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

Page 10: Chapter 7 Java Server Pages

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

%>

Page 11: Chapter 7 Java Server Pages

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

Page 12: Chapter 7 Java Server Pages

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

Page 13: Chapter 7 Java Server Pages

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

Page 14: Chapter 7 Java Server Pages

JSP Life-Cycle

Page 15: Chapter 7 Java Server Pages

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

Page 16: Chapter 7 Java Server Pages

JSP Errors

• Compilation errors and run-time exceptions are logged and then returned as an HTML response

???

Page 17: Chapter 7 Java Server Pages

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

Page 18: Chapter 7 Java Server Pages

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>

Page 19: Chapter 7 Java Server Pages

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

Page 20: Chapter 7 Java Server Pages

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

Page 21: Chapter 7 Java Server Pages

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

Page 22: Chapter 7 Java Server Pages

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

Page 23: Chapter 7 Java Server Pages

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

Page 24: Chapter 7 Java Server Pages

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

Page 25: Chapter 7 Java Server Pages

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

Page 26: Chapter 7 Java Server Pages

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

Page 27: Chapter 7 Java Server Pages

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

Page 28: Chapter 7 Java Server Pages

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>

Page 29: Chapter 7 Java Server Pages

Review

• Java Server Pages

• JSP life-cycle

• JSP Elements

• JSP include and forward directives

• Java Beans with JSP

• JSP taglibs