570 likes | 577 Vues
Java Server Pages. JSP. Topics. JSP Overview JSP and Java Beans Servlet Integration JSP Scripting Custom Tags JSP and WARs/EARs. JSP Overview. Document-centric specification similar to HTML markup code embedded in the document directives actions scripts
E N D
Java Server Pages JSP JavaServer Pages
Topics • JSP Overview • JSP and Java Beans • Servlet Integration • JSP Scripting • Custom Tags • JSP and WARs/EARs JavaServer Pages
JSP Overview • Document-centric specification • similar to HTML • markup code embedded in the document • directives • actions • scripts • Java is the currently supported scripting language • Complementary to servlets JavaServer Pages
JSP Example <HTML> <HEAD><TITLE>JSP Example</TITLE> <%@ page import="java.util.Date" %> </HEAD> <%-- Embed Date in generated output --%> <BODY> The Date is: <%= new Date() %> </BODY> </HTML> JavaServer Pages
JSP Components • JSP Tags • Comments • Scripting elements • Actions • Directives JavaServer Pages
JSP Comments • JSP comments are stripped out and do not appear in the generated HTML page <%-- This is a JSP comment --%> • HTML comments are supported and do appear in the generated HTML page <!-- This is an HTML comment --> JavaServer Pages
JSP Directives • Instructions for JSP Container • Processed when JSP page is converted to a servlet • Directives do not cause information to be written to JSPs output • Shorthand Form <%@ page import=“javax.naming.*” %> • XML Form <jsp:directive.page import=“javax.naming.*” /> JavaServer Pages
JSP Page Directives • Page directive attributes • info - defines string returned from Servlet.getServletInfo() • language - only required language is java • contentType - defaults to “text/html;charset=ISO-8859-1” <jsp:directive.page contentType=“text/xml”/> • extends - specifies the base class of the generated servlet • generally not a good idea, limits the container implementation options • import - specifies classes to import for scriptlets/beans <jsp:directive.page import=“package.Class”/> JavaServer Pages
JSP Page Directives (cont.) • Page directive attributes (Cont) • session - defines implicit HttpSession session variable <jsp:directive.page session=“true”/> • buffer - specifies size of output buffer • autoFlush - flushes (true) buffer when full;throws (false) exception • isThreadSafe - dispatches requests in single thread (false) or multiple threads (true). Default is true. • isErrorPage - defines implicit java.lang.Throwable exception variable <jsp:directive.page errorPage=“true”/> • errorPage - specifies JSP to invoke on uncaught exceptions • <jsp:directive.page errorPage=“/ErrorPage.jsp”/> JavaServer Pages
JSP Include Directives • Static includes done at deployment <@ include file=“fileRelativeURL” %> <jsp:directive.include file=“fileRelativeURL” /> • Same as #include is C/C++ • Imagine a page: • <jsp:directive.include file=“Header.jsp” /> • < jsp:directive.include file=“Body.jsp” /> • < jsp:directive.include file=“Footer.jsp” /> • Another form may be done at runtime<jsp:include page=“pageRelativeURL”/> JavaServer Pages
JSP Declarations • Create variables (or methods) for later use in expressions or scriptlets <%! String choice; %> <jsp:declaration> String choice; </jsp:declaraion> • Code is inserted in generated servlet outside of service() method. • Object-level scope • Example <jsp:declaration> int i=0; void print() { System.out.println(i++); } <jsp:declaration> <jsp:scriptlet>print();<jsp:scriptlet> JavaServer Pages
Scriptlets • Code to be inserted directly in the generated servlet and executed when page is requested • i.e. inserted in service method <% choice = request.getParameter(“Product”); %> <jsp:scriptlet> choice=request.getParameter(“Product”); </jsp:scriptlet> • Default scripting language is Java so all conditional statements, method invocations, etc. are supported JavaServer Pages
Expressions • Insert results from code execution directly onto the JSP Page <P> The Date is: <%= new Date() %> </P> <P> The Date is: <jsp:expression>new Date()</jsp:expression> </P> • Automatically converts toString() and writes result JavaServer Pages
Implicit Objects • page • Page’s servlet instance • config • ServletConfig (configuration data) • request • HttpServletRequest • response • HttpServletResponse JavaServer Pages
Implicit Objects (Cont) • out • Output Stream for content (JspWriter) • session • HttpSession • application • ServletContext • pageContext • Context Data for page execution (PageContext) • exception • Available on error pages (java.lang.Throwable) JavaServer Pages
Implicit Object Example <HTML> <BODY> <% String visitor=request.getParameter(“name”); if( visitor==null) visitor=“Unknown”; %> Hello, <%= visitor %> </BODY> </HTML> • http://localhost:7001/jsp/implicit.jsp?name=Dan • Remember: Keep URLs shorter than 255 characters JavaServer Pages
JSP-Specific Tags • jsp:forward • Switch to another URL • jsp:include • Embed the contents of another URL in this page • jsp:useBean, jsp:setProperty, jsp:getProperty • Embed and use JavaBeans in a JSP Page • jsp:plugin • downloads Java plugin to client JavaServer Pages
Risks • Embedding code in the HTML page is convenient, but …. • We are mixing business logic with presentation • Use JSP for simple coding e.g. Date • Defer business logic to Beans and or Servlets JavaServer Pages
JSP and Java Beans JavaServer Pages
What is a Bean? • Java class that follows a set of implementation and naming guidelines • Typically named xxxBean • Public no argument constructor • Setters/Getters for attributes • Indexed properties • BeanInfo interface • Should implement java.io.Serializable • Event model, bound and constrained properties JavaServer Pages
HelloBean packages corej2ee.examples.web.usebean; public class HelloBean implements java.io.Serializable { String name; public HelloBean() { name=“Anonymous”; } public String getName() { return name; } public void setName(String argName) { name=argName; } } JavaServer Pages
usebean.html <html> <head><title>Test of jsp use bean></title></head> <body> <h1>Enter Name</h1> <form action="usebean.jsp" method="POST"> <table border="0" width="30%" cellspacing="3" cellpadding="2"> <tr><td><b>User Name</b></td> <td><input type="text" size="20" name="name"></td></tr> <tr><td><p><input type="submit" value="Login"></td></tr> </table> </form> </body> </html> JavaServer Pages
Using Java Beans in JSP <jsp:useBean id="hellobean" class="corej2ee.examples.web.usebean.HelloBean"/> <jsp:setProperty name=“hellobean” property="name" param="name"/> <HTML> Hello, <jsp:getProperty name="hellobean" property="name"/> <BODY> </BODY> </HTML> JavaServer Pages
Setting Bean Attributes • jsp:setProperty tag • Can initialize bean properties from HttpRequest <jsp:setProperty name=“hello” property=“name” param=“name”/> • Param attribute (from form) is the equivalent of: request.getParameter(“name”); • Property attribute (from JavaBean) is equivalent of: hello.setName(…); • Shortcut to set all parameters in bean that match request parameter names <jsp:setProperty name=“hello” property=“*”/> • Use value attribute to set the property to a specific value • property=“name” value=“hard-coded-value” JavaServer Pages
Bean Scope • Bean lifetime defaults to the execution of the page that contains the useBean tag • scope= • “page” - defined in jsp.PageContext • “request” - defined in Servlet.service()’s request object • (jsp:forward, jsp:include) • “session” - defined in user’s session object • “application” - defined in Servlet’s Context • Interesting servlet/jsp communication mechanism JavaServer Pages
Benefits and Limitations • Benefits • Separates business logic from HTML content • Easier maintenance • Component Re-usability • Can be configured with commercial tools • Limitations • Java Bean event model not supported JavaServer Pages
JSP Summary • Allows HTML authors to be HTML authors and not Java programmers • While Java code can be embedded in the .jsp page this should be kept to a minimum • Use JavaBeans for model data and tags as the interface between the html page and the model • Avoid HTML output from Beans • Custom Tags are useful for generating HTML JavaServer Pages
JSP Custom Tags JavaServer Pages
JSP Tags Overview • Capability to define your own jsp tags in a portable manner • Required components • Tag Handler class • Implements tag behavior • Tag Library Descriptor File • Define class to server and associate it with an XML tag name • XML document JavaServer Pages
Tag Handler • Must implement the javax.servlet.jsp.tagext.Tag interface • doStartTag() and doEndTag() are key methods • Frequently extend TagSupport JavaServer Pages
package corej2ee.examples.web.tag; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; import javax.servlet.*; /** A tag that includes the body content only if * the "debug" request parameter is set. * <P> * Taken from Core Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.coreservlets.com/. * © 2000 Marty Hall; may be freely used or adapted. */ public class DebugTag extends TagSupport { public int doStartTag() { ServletRequest request = pageContext.getRequest(); String debugFlag = request.getParameter("debug"); if ((debugFlag != null) && (!debugFlag.equalsIgnoreCase("false"))) { return(EVAL_BODY_INCLUDE); } else { return(SKIP_BODY); } } } Handler Example (DebugTag.java) JavaServer Pages
TagLib Descriptor FileWEB-INF/csajsp-taglib.tld <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>csajsp</shortname> <uri></uri> JavaServer Pages
WEB-INF/csajsp-taglib.tld (Cont) <info> A tag library from Core Servlets and JavaServer Pages, http://www.coreservlets.com/. </info> <tag> <name>debug</name> <tagclass>corej2ee.examples.web.tag.DebugTag</tagclass> <bodycontent>JSP</bodycontent> <info>Includes body only if debug param is set.</info> </tag> </taglib> JavaServer Pages
web.xml entry <?xml version="1.0" ?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN " "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <taglib> <taglib-uri>csajsp-taglib.tld</taglib-uri> <taglib-location>WEB-INF/csajsp-taglib.tld</taglib-location> </taglib> </web-app> JavaServer Pages
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Illustration of SimplePrimeTag tag. Taken from Core Servlets and JavaServer Pages from Prentice Hall and Sun Microsystems Press, http://www.coreservlets.com/. © 2000 Marty Hall; may be freely used or adapted. --> <HTML> <HEAD> <TITLE>Using the Debug Tag</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Using the Debug Tag</H1> <%@ taglib uri="csajsp-taglib.tld" prefix="csajsp" %> Top of regular page. Blah, blah, blah. Yadda, yadda, yadda. <P> <csajsp:debug> <B>Debug:</B> <UL> <LI>Current time: <%= new java.util.Date() %> <LI>Requesting hostname: <%= request.getRemoteHost() %> <LI>Session ID: <%= session.getId() %> </UL> </csajsp:debug> <P> Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda. </BODY></HTML> DebugExample.jsp JavaServer Pages
Invoking debug.jsp JavaServer Pages
Invoking debug.jsp with Debug JavaServer Pages
Tag Complexity • Tags can become very complicated • Can parse body themselves • Can become nested in other tags • Ex. IF/THEN/ELSE • Looping constructs • While beans are generally used for model data and shared information, tags are typically confined to a single page JavaServer Pages
Tag Summary • Tags are a portable extension mechanism for jsp • Can build a library of components • Ex. XSLT renderer of XML data • Bridge to JavaBean model data • Ex. Setting indexed properties • Further eliminates the need for HTML authors to learn Java JavaServer Pages
JSTL and Expression Language Optional Topic JavaServer Pages
JSP Standard Tag Library • Encapsulates core functionality for many web applications in custom tags • http://java.sun.com/products/jsp/jstl • Requires JSP 1.2 • Custom tags • Iteration, Control, Internationalization, Database Access • Expression language to simplify page development JavaServer Pages
JSTL Libraries • Core • XML Processing • I18N • Database Access JavaServer Pages
Expression Language • Simpler syntax for accessing Java Bean properties • Similar to JavaScript • ${customerBean}.name$ • ${customerBean}[“name”]}$ • customerBean is in one of the JSP’s scopes • page, request, session, or application • Implicit variables also available • param – collection of all request parameters • cookie – collection of all cookies • header – collection of all request headers JavaServer Pages
Basic Example (e1.jsp) <%@ taglib uri="myTLD" prefix="c" %> <html> <head> <title>JSTL: Basic EL Support</title> </head> <body bgcolor="#FFFFFF"> JavaServer Pages
<h1>Basic EL examples</h1> ${cookie.JSESSIONID.value}: <c:out value="${cookie.JSESSIONID.value}" /> <BR> ${param['name']}: <c:out value="${param['name']}" /> <BR> ${header['User-Agent']}: <c:out value="${header['User-Agent']}" /> <BR> </body> </html> JavaServer Pages
Iteration Example (IterateSetup.jsp) <%@ page import="corej2ee.examples.web.jspstl.*, java.util.List, java.util.ArrayList" %> <% STLPerson person=new STLPerson(); person.setName("Dan"); person.setStreet("Poplar Ridge"); person.setZip("21122"); JavaServer Pages
STLPerson person2=new STLPerson(); person2.setName("Jim"); person2.setStreet("Severna Park"); person2.setZip("21046"); List peopleList=new ArrayList(); peopleList.add(person); peopleList.add(person2); request.setAttribute("people", peopleList); %> <jsp:include page="Iterate.jsp" /> JavaServer Pages
Iterate.jsp <%@ taglib uri="myTLD" prefix="c" %> <html> <head> <title>JSTL: Iteration Example</title> </head> <body bgcolor="#FFFFFF"> <h3>Simple Iteration</h3> <h4>People list</h4> JavaServer Pages