36
Ch 4 – JavaServer Pages COSC 617 Jeff Schmitt September 28, 2006

Ch 4 – JavaServer Pages COSC 617 Jeff Schmitt September 28, 2006

Embed Size (px)

Citation preview

Ch 4 – JavaServer Pages

COSC 617

Jeff Schmitt

September 28, 2006

ServletsAdvantages Disadvantages

• Scalable• Persistent• Simple• Flexible• Support• Stable API• Run in separate

memory space from Server

• 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

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

Servlet Sequence Diagram

Client Webserver Servlet

request() init()

destroy()

service()

Process requestresponseresponse

Servlet Multithreading

Client 1 Servlet

request

Client 2

request

response

response

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

Classical Model-View-Controller Architecture

View

Controller

Model

Example: A Clock Application

Change Notification

User Events

Select a ViewModel Changes

Model Queries

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

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

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

CacheFreemarkerModelRoot

Resulting

web page

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

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

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)

JSP Lifecycle

Client Webserver Servlet

request

service()

init()

Process requestresponse

response

JSP

request JSP to ServletCompile Servletservlet

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>

JSP Default ObjectsObject 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

JSP Object ScopeScope 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

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

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>

JSP Forward

Client Webserver Servlet 1

request

service()

Process request

responseresponse

JSP

request JSP to ServletCompile Servletservlet

Servlet 2

request JSP to ServletCompile Servletservlet

Process request

service()

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

date.jsp

NoteNote: <%! For declarations, global to all invocations

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

Objects avalable in JSP

• application ServletContext• config ServletConfig• exception Throwable• out JspWriter• page Object• pageContext PageContext• request HttpServletRequest• response HttoServletResponse• session HttpSession

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)

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

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

JavaBean Scope

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

JSP Expression Language

• EL for short

• JSP engine evaluates the expression and embeds the result in the page

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

product.jsp

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

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>

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>

JSTL I18n

• JSTL fmt (not core) tag lib

• External Properties File

• message_en.properties– first.name=First Name– last.name=Last Name

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>

Wrapping Up

• Questions?