1 / 36

Ch 4 – JavaServer Pages

Ch 4 – JavaServer Pages. COSC 617 Jeff Schmitt September 28, 2006. Servlets Advantages Disadvantages. Servlet mapping (servlet is not a web page) Hard for Web Designer to change the HTML part of the code HTML (presentation) and Java code (business logic) mixed together. Scalable

echo-hobbs
Download Presentation

Ch 4 – JavaServer 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. Ch 4 – JavaServer Pages COSC 617 Jeff Schmitt September 28, 2006

  2. ServletsAdvantages Disadvantages • Servlet mapping(servlet is not a web page) • Hard for Web Designer to change the HTML part of the code • HTML (presentation) and Java code (business logic) mixed together • Scalable • Persistent • Simple • Flexible • Support • Stable API • Run in separate memory space from Server

  3. HTML-based interfaces with servlets • Time consuming • Strings of println statements • Configuration files • Changes are error prone • Requires a programmer • Prefer to use a web designer • One approach – use HTML except for forms processing -- limitations

  4. request() init() service() Process request response response destroy() Servlet Sequence Diagram Client Webserver Servlet

  5. request request response response Servlet Multithreading Client 1 Servlet Client 2

  6. Better approach • Blend dynamic elements directly into the static content • The reverse of the approach servlets use • Use HTML development tool to edit the page (it should ignore the embedded dynamic content tags) • Two approaches • Document templates • JSP

  7. Classical Model-View-Controller Architecture Model Queries View Model Change Notification User Events Select a View Model Changes Controller Example: A Clock Application

  8. Problems with JSP • Although intended to help separate the presentation logic (VIEW) from the business logic (MODEL), JSP does not go far enough • JSP programs are often a mix of HTML and business logic, which creates a problem if the design of the page (VIEW) needs to be changed • HTML changes need to be made by web designers who are not necessarily programmers • Solutions to this problem include WebMacro, Struts, FreeMarker, Velocity

  9. Document templates • Template file is HTML with special tags • Template file is run through server-side processor which replaces tags with dynamic content • Example: WebMacro and Velocity • JSP – Sun’s approach • Built on top of Servlet API • Compiled to Servlet • An “Inside-out” servlet

  10. FreeMarker Template Processing • Makes substitutions of text in a template based on a set of identifiers in a table ModelRoot) • Works with any form of text files including HTML, XML. and Data files Template Cache ModelRoot Freemarker Resulting web page

  11. Freemarker Template Scripting • Value Substitution from rootHash${request.NAME} • Freemarker Comments<comment> . . . </comment> • List iteration<loop guestbook as entry> . . . </list> • Conditional<if> . . . <else> . . . </if> • Text inclusion from another template file<include "footer.html">

  12. FreeMarker Template Cache • Manages the folder where templates are stored • Loads and compiles templates into tokenized form for efficiency • Recognizes changes to templates while application is running

  13. JSP -- Java Server Pages • Similar to servlets, but they resemble HTML pages • Placed in web folders mixed with HTML files, acts like an HTML file • Compiled automatically to a servlet when first referenced or when the file is changed by programmer. • Intended to help separate the presentation (HTML response) from the logic (processing logic). • Similar to Microsoft's Application Server Pages (ASP)

  14. request request JSP to Servlet Compile Servlet servlet init() service() Process request response response JSP Lifecycle Client Webserver Servlet JSP

  15. JSP scripting elements • JSP Comments<%-- jsp comment --%> • Declarations: placed in static part of servlet<%! String filePath="/users";%> • Expressions: evaluate to a string<%= request.getParameter("NAME")%> • Scriptlets: any Java statements<% (java statements) %> • Template Text: inserted into response<TABLE BORDER=1><TR><TH>Name:<TD><INPUT NAME="NAME" size=50 MAXLENGTH=50>

  16. JSP Default Objects

  17. JSP Object Scope

  18. Custom JSP tags • Assemble reusable JSP code for easy use • An XML-like front end to access Java programming • Designed to bridge the intersection between java programmers and web designers • Tag library holds definitions of custom tags<%@ taglib uri="jakarta-taglib/dbtags" prefix="sql" %> • Custom tags save in Tag Library File .tld • Many useful Tag Libraries exist for the common tasks such as database access, email, file access

  19. JSP Action Elements • Control Tags for request-time include • Optional parameters for Control tags • Allow JSP programs to implement the Controller aspect of the Model-View-Controller architecture • <jsp:include page="header.jsp"/> • <jsp:forward page="html.jsp/> • <jsp:forward page="html.jsp"> • <jsp:param name="page" value="guestview"/> • </jsp:forward>

  20. request request JSP to Servlet Compile Servlet servlet service() Process request request JSP to Servlet Compile Servlet servlet service() Process request response response JSP Forward Client Webserver Servlet 1 Servlet 2 JSP

  21. date.jsp Note: <%! For declarations, global to all invocations • <html> • <body> • <% • java.util.Date theDate = new java.util.Date( ); • %> • <% if (theDate.getHours( ) < 12) { %> • Good morning, • <% } else { %> • Good afternoon, • <% } %> • visitor. It is now <%= theDate.toString( ) %> • </body> • </html>

  22. JSP Page Directive values • autoFlush buffer flushed when full, true • buffer buffer size in kb • contentType default is text/html • errorPage custon error-handling page • import list of java classes/packages • isErrorPage makes exception object available • session page participates in user session

  23. Objects avalable in JSP • application ServletContext • config ServletConfig • exception Throwable • out JspWriter • page Object • pageContext PageContext • request HttpServletRequest • response HttoServletResponse • session HttpSession

  24. JSP Action Tags • Allow non-programming web designers to develop dynamic content • Action tag looks like regular HTML • Does not follow <% %> syntax • built-in actions • custom tags • <%@ include %> directive • (once at compile time) • <jsp:include page=“/header.jsp”/> • (at request time)

  25. public class Product { private String name = null; private double price = 0.0d; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } static Product makeProduct(String newName, double newPrice) { Product p = new Product(); p.setName(newName); p.setPrice(newPrice); return p; } } JavaBean

  26. JavaBeans • <jsp:useBean id=“product” class=“fontanini.ProductBean” scope=“request”/> • <jsp:setProperty name=“product” property=“ProductID” value=“1234”/> • in setProperty, value can be omitted, accesses request value instead • special property name (*) populates every property of the bean from the request parameters

  27. JavaBean Scope • <jsp:useBean id=“product” class=“fontanini.ProductBean” scope=“request”/> • page (default) • request • session • application

  28. JSP Expression Language • EL for short • JSP engine evaluates the expression and embeds the result in the page

  29. product.jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Product Description</title></head> <body> <h1>${product.name}</h1> Price: $${product.price} <c:if test="${product.price > 400}"> <br/><font color="red">Eligible for Saver Shipping!</font> </c:if> </body> </html>

  30. JSTL Java Standard Tag Library • Easy to incorporate into Web Applications • Necessary jar files go in /WEB-INF/lib • Add to each page: • <%@ taglib uri=http://java.sun.com/jsp/jstl/core” prefix=“c” %>

  31. JSTL variables • <%@ taglib uri="http://java.sun.com/jsp/jstl/core" • prefix="c" %> • <%@ page contentType="text/html;charset=UTF-8" language="java" %> • <html> • <c:set var="username" scope="session" value="${param.username}"/> • <c:out value="${username}"/> • <c:remove var="username"/> • </html>

  32. JSTL Flow Control <%@ page contentType="text/html;charset=UTF-8" language="java" %> • <html> • <head><title>Widget Catalog</title></head> • <body> • <ul> • <c:forEach var="product" items="${catalog}"> • <li>${product.name}: $${product.price}</li> • </c:forEach> • </ul> • </body> • </html>

  33. JSTL I18n • JSTL fmt (not core) tag lib • External Properties File • message_en.properties • first.name=First Name • last.name=Last Name

  34. message.jsp • <%@ taglib uri=http://java.sun.com/jsp/jstl/fmt prefix="fmt" %> • <form> • <fmt:bundle basename="messages"> • <table> • <tr><td> • <fmt:message key="first.name"/> • </td><td><input type="text" name="firstname"></td></tr> • <tr><td> • <fmt:message key="last.name"/> • </td><td><input type="text" name="lastname"></td></tr> • </table> • </fmt:bundle> • <input type="submit" value="Submit"> • </form>

  35. Wrapping Up • Questions?

More Related