Download presentation
Presentation is loading. Please wait.
1
COSC 617 Jeff Schmitt September 28, 2006
Ch 4 – JavaServer Pages COSC 617 Jeff Schmitt September 28, 2006
2
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 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
Servlet Sequence Diagram
Client Webserver Servlet request() init() service() Process request response response destroy()
5
Servlet Multithreading
Client 1 Servlet Client 2 request request response response
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
14
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)
15
JSP Lifecycle Client Webserver Servlet JSP request request servlet
JSP to Servlet Compile Servlet servlet service() init() Process request response response
16
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>
17
JSP Default Objects Object Class Scope Comments request
HttpServletRequest Request The client request response HttpServletResponse Page The servlet response out JspWriter page An object for writing to the output stream session HttpSession Session Created to track same user as they visit and return to pages in web application application ServletContext Application Allows servlets to communicate with each other
18
JSP Object Scope Scope Meaning Page
Available to the handling page only Request Available to the handling page and to any servlelt or JSP that control is forwarded to or included Session Available to any servlet or JSP within the same session (across repeat visits to web application) Application Available to any servlet or JSP within the same web application
19
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, , file access
20
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>
21
JSP Forward Client Webserver Servlet 1 Servlet 2 JSP request request
JSP to Servlet Compile Servlet servlet service() Process request request JSP to Servlet Compile Servlet servlet Process request service() response response
22
date.jsp <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> Note: <%! For declarations, global to all invocations
23
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
24
Objects avalable in JSP
application ServletContext config ServletConfig exception Throwable out JspWriter page Object pageContext PageContext request HttpServletRequest response HttoServletResponse session HttpSession
25
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)
26
JavaBean 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
27
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
28
JavaBean Scope <jsp:useBean id=“product” class=“fontanini.ProductBean” scope=“request”/> page (default) request session application
29
JSP Expression Language
EL for short JSP engine evaluates the expression and embeds the result in the page
30
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>
31
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= prefix=“c” %>
32
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>
33
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>
34
JSTL I18n JSTL fmt (not core) tag lib External Properties File
message_en.properties first.name=First Name last.name=Last Name
35
message.jsp taglib uri= prefix="fmt" %> <form> <fmt:bundle basename="messages"> <table> <tr><td> <fmt:message key="first.name"/> </td><td><input type="text" name="firstname"></td></tr> <fmt:message key="last.name"/> </td><td><input type="text" name="lastname"></td></tr> </table> </fmt:bundle> <input type="submit" value="Submit"> </form>
36
Wrapping Up Questions?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.