1 / 29

Chapter 7 Java Server Pages

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

woody
Download Presentation

Chapter 7 Java Server Pages

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7Java Server Pages

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

  3. Separation of Concerns • A basic principle of software design:Software modules should have distinct responsibilities as much as possible input data retrieval calculation output

  4. Separation of ContentFrom Processing (1/2) • A servlet generating an HTML document intermixes Java code and HTML public 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();}

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

  6. JSP Elements • JSP tags belong to one of five element types Declaration: 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

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

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

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

  10. 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>"; %>

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

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

  13. 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 JSP Servlet translated upon first request

  14. JSP Life-Cycle

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

  16. JSP Errors • Compilation errors and run-time exceptions are logged and then returned as an HTML response ???

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

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

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

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

  21. 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 is continued after the directive, which is not a Java statement

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

  23. Java Bean Example • Java Bean package 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); %>

  24. Java Bean Uses • Java Beans are typically used to encapsulate complex application logic, including calculations, database access, or network access Application Java Bean JSP Database Network

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

  26. Taglib Example • JSP code: <tags:boxin border="green"> This code appears in a green box </tags:boxin> tag body content This code appears in a green box

  27. Taglib Example • BoxInTag.java public 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 body content, i.e., the text between the tag opening and closing

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

  29. Review • Java Server Pages • JSP life-cycle • JSP Elements • JSP include and forward directives • Java Beans with JSP • JSP taglibs

More Related