Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
(Server-Side Programming using Java Server Pages) cs236607 1 cs236607 2 Motivation Software components (e.g. objects, data structures, primitives) are extensively used in Web applications For example: Service local variables Attributes forwarded in requests Session attributes, such as user information Application attributes, such as access counters See tutorial at http://java.sun.com/docs/books/tutorial/javabeans/ 3 cs236607 Motivation Standard actions are used to manipulate components: declaration, reading from the suitable context, setting of new values (according to input parameters), storing inside the suitable context, etc. Java Beans provide a specification for automatic handling and manipulation of software components in JSP (and other technologies...) 4 cs236607 Java Beans: The Idea Java Beans are simply objects of classes that follow some (natural) coding convention: An empty constructor A readable property has a matching getter A writable property has a matching setter Use JSP actions to access and manipulate the bean, and special action attributes to specify the properties of the bean, e.g., its scope JSP programmers do not wish to write cumbersome code or class files 5 cs236607 Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages 6 cs236607 Counter Bean Bean must reside in a package A Bean is a concept and therefore there’s no need to extend any class or implement any interface! (though it would’ve been package myUtils; very Java-ish to create an empty interface “Bean”) public class CounterBean { A Bean is created private int counter; by an empty public CounterBean() { counter = 0; } constructor public int getCounter() { return counter; } public void setCounter(int i) { counter = i; } public void increment() { ++counter; } Counter setter and getter } Other methods can be implemented as well 7 cs236607 CounterBean.java <html> The default <head><title>Bean Example</title></head><body> scope is page <jsp:useBean id="accessCounter" class=“myUtils.CounterBean" scope="application"/> You could also use the type attribute in order to instantiate a data type which is either superclass of class or an interface that class implements An instance named according to the given id is either found in the relevant scope or is created <% accessCounter.increment(); %> <h1> Welcome to Page A</h1> <h2>Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> </h2> <a href="pageB.jsp">Page B</a></body> Invokes getCounter() </html> pageA.jsp 8 cs236607 <html> <head><title>Bean Example</title></head><body> <jsp:useBean id="accessCounter" class=“myUtils.CounterBean" scope="application"/> Since an instance named according to the given id can be found in the application scope, no instantiation takes place <% accessCounter.increment(); %> <h1> Welcome to Page B</h1> <h2>Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> </h2> <a href="pageA.jsp">Page A</a></body> pageB.jsp </html> A very similar JSP 9 cs236607 Part of the Generated Servlet myUtils.CounterBean accessCounter = null; synchronized (application) { The instance is created and kept in the application’s scope as required. Note however that accessing this instance is out of the synchronized scope accessCounter = (myUtils.CounterBean) _jspx_page_context.getAttribute("accessCounter", PageContext.APPLICATION_SCOPE); Similar effect to if (accessCounter == null) { getServletContext().getAttribute() accessCounter = new myUtils.CounterBean(); _jspx_page_context.setAttribute("accessCounter", accessCounter, PageContext.APPLICATION_SCOPE); } } 10 cs236607 Similar effect to getServletContext().setAttribute() Example 2: Session Data In the following example, we use a Bean in order to keep a user's details throughout the session 11 cs236607 package myUtils; public class UserInfoBean { private String firstName; private String lastName; public UserInfoBean() { firstName = lastName = null;} public String getFirstName() {return firstName;} public String getLastName() {return lastName;} public void setFirstName(String string) {firstName = string;} public void setLastName(String string) {lastName = string;} } 12 UserInfoBean.java cs236607 <html> <head><title>Information Form</title></head> <body> <h1>Fill in your details:</h1> <form action="infoA.jsp" method="get"><p> Your First Name: <input type="text" name="firstName" /> <br/> Your Last Name: <input type="text" name="lastName" /><br/> <input type="submit" /></p> </form> </body></html> 13 cs236607 infoForm.html <jsp:useBean id="userInfo" class=“myUtils.UserInfoBean" scope="session"/> <jsp:setProperty name="userInfo" property="*"/> The String values are converted to the right bean’s property types.. <html> Match all the request parameters to corresponding properties. You could match parameters to properties explicitly using property=… param=… <head><title>Page A</title></head><body> <h1>Hello You can also set properties with explicit values using property=… value=… <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, </h1> <h1>Have a nice session!</h1> <h2> <a href="infoB.jsp">User Info B</a></h2> </body></html> cs236607 14 infoA.jsp <jsp:useBean id="userInfo" class=“myUtils.UserInfoBean" scope="session"/> <jsp:setProperty name="userInfo" property="*"/> <html> This time the request has no parameters so no bean properties are set <head><title>Page B</title></head><body> <h1>Hello <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, </h1> A very similar JSP <h1>Have a nice session!</h1> <h2> <a href="infoA.jsp">User Info A</a></h2> </body></html> 15 cs236607 infoB.jsp Advantages of Java Beans Easy and standard management of data Automatic management of bean sharing and lots more Good programming style Allow standard but not direct access to members You can add code to the setters and getters (e.g. constraint checks) without changing the client code You can change the internal representation of the data without changing the client code Increase of separation between business logic (written by programmers) and HTML (written by GUI artists) 16 cs236607 cs236607 17 Custom JSP Tags JSP code may use custom tags – tags that are defined and implemented by the programmer The programmer defines how each of the custom tags is translated into Java code There are two methods to define custom tags: Tag libraries - used in old versions of JSP Tag files - much simpler, introduced in JSP 2.0 18 cs236607 Tag Libraries A tag library consists of: Tag handlers - Java classes that define how each of the new tags is translated into Java code A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag (see a tutorial at http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html) 19 cs236607 A Simple TagLib Example • Goal: <mytag:date/> The java file is placed in webapps/myapp/WEB-INF/src/my/ We must use a package (not necessarily named like your application) since this is a helper class which is imported form the JSP’s generated Servlet that is placed within a named package The class file is placed in webapps/myapp/WEB-INF/classes/my/ DateTag.java package my; Base class of import javax.servlet.jsp.JspException; tags which import javax.servlet.jsp.tagext.SimpleTagSupport; don’t handle the body or the import java.io.IOException; attributes public class DateTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().print(new java.util.Date()); Using the JSP-context, You can also } acquire other implicit objects by calling getSession(), getRequest() } 20 cs236607 etc… Set this value that indicates your tag library version <taglib> <tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version> <tag> <name>date</name> Name of the tag Tag’s class file in /myapp/WEB-INF/classes/my/ <tagclass>my.DateTag</tagclass> This defined tag contains <body-content>empty</body-content> no body The prefix for this tag must appear </tag> before the tag itself (looks like a You can add here namespace). </taglib> more tags… my-taglib.tld The Prefix can’t be empty <%@ taglib prefix=“mytag" uri="/WEB-INF/tags/my-taglib.tld" %> <html><body> <h1>Hello. The time is: <mytag:date/></h1> </body></html> 21 The path could be a URL. If you choose to use a local path, it must begin with /WEB-INF/tags/ cs236607 As you can see from the path, the taglib is taglibuse.jsp specifically defined to the current application context. Taglib with Attributes package my; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import java.io.IOException; public class DateTag2 extends TagSupport { private boolean isLongFormat = false; This member’s name should be identical to the attribute’s. setIsLongFormat(boolean b) The setter/getter methods should be named after the attribute (i.e. “get” + capital (<attribute>)) public void isLongFormat = b; } public boolean getIsLongFormat() { return isLongFormat; { 22 cs236607 { Base class of tags which do handle attributes In our example the attribute is defined as not required so it must have a default value Attribute’s setter method Attribute’s getter method DateTag2.java public int doStartTag() throws JspException { Invoked when the generated Servlet starts processing the “start tag” try { if (isLongFormat) { pageContext.getOut().print(new java.util.Date().getTime()); } else { pageContext.getOut().print(new java.util.Date()); } } Prints the date according to the isLongFormat attribute catch (Exception e) { throw new JspException("DateTag: " + e.getMessage()); } return SKIP_BODY; } Signals the generated Servlet public int doEndTag() { return EVAL_PAGE; } the generated Servlet to } Signals continue executing the generated 23 Servlet code cs236607 there’s no body within the tag to process Invoked when the generated Servlet starts processing the “end tag” <tag> <name>date2</name> <tagclass>my.DateTag2</tagclass> <body-content>empty</body-content> Same as before, only with different names for the tagclass You can put several blocks one after another <attribute> <name>isLongFormat</name> <required>false</required> </attribute> </tag> The attribute is “not required” so you have to define a default value in DateTag2.java my-taglib2.tld <%@ taglib prefix=“mytag" uri="/WEB-INF/tags/my-taglib2.tld" %> <html><body> Uses default attribute value <h1>Hello.</h1> <h2>The time is: <mytag:date2/></h2> <h2>Milliseconds since the epoch : <mytag:date2 isLongFormat="true" /></h2> </body></html> 24 Uses a given attribute value cs236607 taglibuse2.jsp How does it work? taglibuse2_jsp.java Create the JspContext taglibuse2.jsp JSP to Java Servlet translation The attribute value is set using the setter method. The translator actually translated the attribute string value as it appears in the JSP source, to a boolean value as the Java tag class expects it… 25 When the translation engine first encounters <mytag:date2> it creates a new instance of DateTag2 (so we needn’t worry about concurrency issues) and passes it the JspContext reference “Start tag” is reached JspContext DateTag2 setIsLongFormat() doStartTag() doEndTag() “End tag” is reached cs236607 Tag Files JSP 2.0 provides an extremely simplified way of defining tags The motivation: JSP programmers prefer not to write cumbersome code or class files The idea: for each custom tag, write a tag file tagName.tag that implements the tag translation using JSP code This way, the programmer can avoid creating tag handlers and TLD files 26 cs236607 The Simplified Example <%= new java.util.Date() %> date.tag <%@ taglib prefix=“mytag" tagdir="/WEB-INF/tags/" %> <html> <body> In this new mechanism we use tagdir instead of uri we used in the old taglib implementation <h1>Hello. The time is: <mytag:date/></h1> </body> </html> 27 taguse.jsp cs236607 The Attributes Example A new directive <%@ attribute name="isLongFormat" required="false" %> date3.tag <%!private String createDate(String isLong) { Default and Private method isLongFormat=“false” declaration case if ((isLong == null) || (isLong.equals("false"))) { return new java.util.Date().toString();} else { return new Long(new java.util.Date().getTime()).toString();} } %> <%=createDate(isLongFormat)%> Calls the private method isLongFormat=“true” case The isLongFormat parameter is identified as the isLongFormat attribute because we used the attribute directive <%@ taglib prefix=“mytag" tagdir="/WEB-INF/tags/" %> <html><body> Default case <h1>Hello.</h1> <h2>The time is: <mytag:date3/></h2> <h2>Milliseconds since the epoch : <mytag:date3 isLongFormat="true" /></h2> </body></html> 28 isLongFormat=“true” cs236607 taguse3.jsp Other Capabilities of Custom Tags Attributes You can add validation mechanism for the attributes values Tag Body Tag translation may choose to ignore, include or change the tag body 29 cs236607 cs236607 30 JSP Expression Language JSP expression language is a comfortable tool to access useful objects in JSP This language provides shortcuts in a somewhat JavaScript-like syntax An expression in EL is written as ${expr} For example: Hi, ${user}. <em style="${style}">Welcome</em> Note that the EL expression does not violate the XML syntax as opposed to <%= expression %> 31 cs236607 EL Variables JSP EL does not recognize JSP's implicit objects, but rather has its own set Each of these objects maps names to values Map a parameter name to a single value or to multiple values param, paramValues, header ,headerValues, Map a header name to a single value or to multiple values cookie, initParam, Maps a cookie name to a single value pageScope, requestScope, Maps a context sessionScope, applicationScope initialization parameter name to a single value For example, use the param[“x”] or param.x to get the value of the parameter x 32 cs236607 EL Variables (cont) A variable that is not an EL implicit object is looked up at the page, request, session (if valid) and application scopes That is, x is evaluated as the first non-null element obtained by executing pageContext.getAttribute("x"), request.getAttribute("x"), etc. Might be confusing. Make sure you know what you’re accessing! 33 cs236607 Object Properties In JSP EL, Property prop of Object o is referred to as o[prop] Property prop of Object o is evaluated as follows: If o is a Map object, then o.get(prop) is returned If o is a List or an array, then prop is converted into an integer and o.get(prop) or o[prop] is returned Otherwise, treat o “as a bean”, that is: convert p to a string, and return the corresponding getter of o, that is o.getProp() The term o.p is equivalent to o["p"] 34 cs236607 An Example <% response.addCookie(new Cookie(“nameof",“homer")); session.setAttribute(“homepage", new java.net.URL("http://www.simpsons.com")); String[] strs = {"str1","str2"}; session.setAttribute("arr", strs); %> <html><head><title>JSP Expressions</title></head><body> <form method="get" action="el.jsp"> <h2>Write the parameter x: <input name="x" type="text" /> <input type="submit" value="send" /></h2> </form> </body></html> 35 elcall.jsp cs236607 <%@ page isELIgnored="false" %> The default value is TRUE <html> ${…} means evaluate the expression inside the {} <head><title>EL Examples</title></head> <h1>Expression-Language Examples</h1> <h2>Parameter <code>x</code>: ${param["x"]} </h2> <h2>Cookie <code>name</code>: ${cookie.nameof.value}</h2> cookie[“nameof”].getValue() <h2>Header <code>Connection</code>: header [“Connection”] ${header.Connection} </h2> sessionScope[“homepage”]. <h2>Path of session attr. <code>homepage</code>: getPath(). ${sessionScope.homepage.path}</h2> You can omit the sessionScope <h2>Element <code>arr[${param.x}]</code>: ${arr[param.x]} </h2> </body></html> 36 sessionScope[“arr”][param[“x”] cs236607 Only the ${param.x} is evaluated el.jsp cs236607 37 Simple XML Production Ordinary XML declarations Link with XSL stylesheet <?xml version="1.0"?> <!DOCTYPE colors SYSTEM "colors.dtd"> <?xml-stylesheet type="text/xsl" href="colors.xsl"?> <%! static String[] colors = {"red","blue","green"}; %> <%@ page contentType="text/xml" %> JSP directive which <colors> sets the MIME-type of the result… <% for(int i=0; i<3; ++i) { %> <color id="<%=i%>"><%= colors[i] %></color> <% } %> </colors> 38 cs236607 Generated XML <?xml version="1.0"?> <!DOCTYPE colors SYSTEM "colors.dtd"> <?xml-stylesheet type="text/xsl" href="colors.xsl"?> <colors> <color id="0">red </color> <color id="1">blue</color> <color id="2">green</color> </colors> 39 cs236607 JSPX Files (JSP Documents) JSPX files are JSP files that have the extension jspx and 40 have XML syntax JSPX files are also referred to as JSP documents Special JSP tags are used to replace non-XML JSP symbols (<%, <%@, etc.) (Tags and EL can help too!) The default content type of JSPX is text/xml (and not text/html) You can also keep the .jsp suffix and tell the container that a JSP file acts as a JSPX file (and therefore its output is of XML type etc.) cs236607 Advantages/Disadvantages of JSPX Since JSPX documents conform to a legal XML structure you can: Check if the document is well formed XML Validate the document against a DTD Nest and scope namespaces within the document Use all kinds of XML tools (e.g. editors) The main disadvantage is JSPX documents they can grow very long and very (very) cumbersome Much ado about nothing? Sometimes the above “advantages” simple aren’t needed or are of little help 41 cs236607 <%= Expression %> <jsp:expression> Expression </jsp:expression> <% Code %> <jsp:scriptlet> Code </jsp:scriptlet> <%! Declaration %> <jsp:declaration> Declaration </jsp:declaration> An empty element <%@ Directive %> 42 cs236607 <jsp:directive.type Attribute="value"/> Problems on the Way to a Legal XML The XML declaration (<?xml version="1.0"?>) and the DOCTYPE definition are now those of the JSPX file. How do we include the declaration+dtd of the original XML document in the result XML? Solution: use the <jsp:output> tag to explicitly require DOCTYPE and XML declarations (next slide…) How do we generate dynamic attribute values and still keep the document well formed? The following line is an illegal XML opening tag: <color id=“<jsp:expression>i</jsp:expression>“> Solution 1: use <jsp:element> for explicit element construction Solution 2: use an EL expression 43 cs236607 <?xml version=“1.0” ?> Namespace of basic JSP elements and Tag libraries.. <colors xmlns:jsp="http://java.sun.com/JSP/Page"> <jsp:output doctype-root-element="colors" Root element + DTD of the resulting XML doctype-system="colors.dtd" /> <jsp:output omit-xml-declaration="false"/> <jsp:declaration> Do not omit the XML declaration of the result static String[] colors = {"red","blue","green"};</jsp:declaration> <jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet> CDATA is <jsp:element name="color"> used because <jsp:attribute name="id"> of <. <jsp:expression>i</jsp:expression> Altenatively: </jsp:attribute> use < <jsp:expression>colors[i]</jsp:expression> </jsp:element> The result is equivalent to the original line: <jsp:scriptlet>} <color id="<%=i%>"><%= colors[i] %></color> </jsp:scriptlet> 44 cs236607 </colors> A Few More Problems on the Way Where can we add an XSL declaration? It should be: outside the root element (colors), but also after jsp:output which must be defined after jsp namespace declaration within the colors element… When using the include directive, the JSP might become illegal XML with more than a single root A solution: Use the <jsp:root> element as the document root Does this solve all the problems which might arise when using the include directive? 45 cs236607 <?xml version=“1.0” ?> <jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"> <jsp:output doctype-root-element="colors" doctype-system="colors.dtd" /> <jsp:output omit-xml-declaration="false"/> Now we can add the XSL <![CDATA[<?xml-stylesheet type="text/xsl" href="colors.xsl"?>]]> We use CDATA because of the <?, ?> etc <colors > <jsp:declaration>static String[] colors = {"red","blue","green"}; </jsp:declaration> <jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet> <jsp:element name="color"> <jsp:attribute name="id"> <jsp:expression>i</jsp:expression></jsp:attribute> <jsp:expression>colors[i]</jsp:expression> </jsp:element> <jsp:scriptlet>}</jsp:scriptlet> Still problematic: Which DTD should we use? </colors> the DTD should enable every JSP element within every other element… </jsp:root> 46 cs236607 Links JSP Tutorial: http://courses.coreservlets.com/Course- Materials/csajsp2.html Advanced Tutorials: http://courses.coreservlets.com/CourseMaterials/msajsp.html JSP API: http://tomcat.apache.org/tomcat-5.5doc/jspapi/ JSP Syntax Reference: http://java.sun.com/products/jsp/syntax/2.0/syntaxref 20.html cs236607 47