1 / 40

Advanced Java Server Pages

Advanced Java Server Pages. Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher. Java Beans in JSP Custom JSP tags - TagLib JSP Expression Language. Agenda. Motivation.

talen
Download Presentation

Advanced Java Server 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. Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher

  2. Java Beans in JSP • Custom JSP tags - TagLib • JSP Expression Language Agenda

  3. 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://docs.oracle.com/javase/tutorial/javabeans/

  4. 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...)

  5. 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

  6. Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages

  7. Counter Bean - CounterBean.java A Bean is a concept and therefore there’s no need to extend any class or implement any interface! (though it would’ve been very Java-ish to create an empty interface “Bean”) Bean must reside in a package • package myUtils; • public class CounterBean { • private int counter; • public CounterBean() { counter = 0; } • public intgetCounter() { return counter; } • public void setCounter(inti) { counter = i; } • public void increment() { ++counter; } • } A Bean is created by an empty constructor Other methods can be implemented as well Counter setter and getter

  8. An instance named according to the given id is either found in the relevant scope or is created <html> <head><title>Bean Example</title></head><body> <jsp:useBean id="accessCounter" class=“myUtils.CounterBean" scope="application"/> <%accessCounter.increment(); %> <h1> Welcome to Page A</h1> <h2>Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> </h2> <ahref="pageB.jsp">Page B</a></body> </html> 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 The default scope is page Invokes getCounter() • pageA.jsp

  9. Counter Bean – cont. <html> <head><title>Bean Example</title></head><body> <jsp:useBean id="accessCounter" class=“myUtils.CounterBean" scope="application"/> <% accessCounter.increment(); %> <h1> Welcome to Page B</h1> <h2>Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> </h2> <ahref="pageA.jsp">Page A</a></body> </html> Since an instance named according to the given id can be found in the application scope, no instantiation takes place • pageB.jsp A very similar JSP

  10. Part of the Generated Servlet 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 • myUtils.CounterBeanaccessCounter = null; • synchronized (application) { • accessCounter = (myUtils.CounterBean) _jspx_page_context.getAttribute("accessCounter", • PageContext.APPLICATION_SCOPE); • if (accessCounter == null) { • accessCounter = new myUtils.CounterBean(); • _jspx_page_context.setAttribute("accessCounter", • accessCounter, PageContext.APPLICATION_SCOPE); • } • } Similar effect to getServletContext().getAttribute() Similar effect to getServletContext().setAttribute()

  11. counter demo

  12. Example 2: Session Data • In the following example, we use a Bean in order to keep a user's details throughout the session

  13. Example 2: Session Data – cont. 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;} } • UserInfoBean.java

  14. Example 2: Session Data – cont. <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> • infoForm.html

  15. Example 2: Session Data – cont. <jsp:useBean id="userInfo" class=“myUtils.UserInfoBean" scope="session"/> <jsp:setProperty name="userInfo" property="*"/> <html> <head><title>Page A</title></head><body> <h1>Hello <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, </h1> <h1>Have a nice session!</h1> <h2><ahref="infoB.jsp">User Info B</a></h2> </body></html> The String values are converted to the right bean’s property types.. Match all the request parameters to corresponding properties. You could match parameters to properties explicitly using property=… param=…You can also set properties with explicit values using property=… value=… • infoA.jsp

  16. Example 2: Session Data – cont. <jsp:useBean id="userInfo" class=“myUtils.UserInfoBean" scope="session"/> <jsp:setProperty name="userInfo" property="*"/> <html> <head><title>Page B</title></head><body> <h1>Hello <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, </h1> <h1>Have a nice session!</h1> <h2><ahref="infoA.jsp">User Info A</a></h2> </body></html> This time the request has no parameters so no bean properties are set A very similar JSP • infoB.jsp

  17. 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)

  18. session demo

  19. Java Beans in JSP • Custom JSP tags - TagLib • JSP Expression Language Agenda

  20. 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

  21. 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)

  22. Date Tag Example • Goal: <mytag:date/> 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 java file is placed in webapps/myapp/WEB-INF/src/my/ The class file is placed in webapps/myapp/WEB-INF/classes/my/ package my; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; publicclassDateTagextendsSimpleTagSupport { publicvoiddoTag() throwsJspException, IOException { getJspContext().getOut().print(newjava.util.Date()); } } Base class of tags which don’t handle the body or the attributes Using the JSP-context, You can also acquire other implicit objects by calling getSession(), getRequest() etc… DateTag.java

  23. Date Tag Example – cont. 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> <tagclass>my.DateTag</tagclass> <body-content>empty</body-content> </tag> </taglib> Name of the tag Tag’s class file in /myapp/WEB-INF/classes/my/ This defined tag contains no body my-taglib.tld

  24. Date Tag Example – cont. You can add here more tags… The prefix for this tag must appear before the tag itself (looks like a namespace). 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> The path could be a URL. If you choose to use a local path, it must begin with /WEB-INF/tags/ taglibuse.jsp

  25. Taglib with Attributes Base class of tags which do handle 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; • public void setIsLongFormat(boolean b) { • isLongFormat = b; } • public boolean getIsLongFormat() { • return isLongFormat; { the attribute is defined as not required so it must have a default value The setter/getter methods should be named after the attribute (i.e. “get” + capital (<attribute>)) This member’s name should be identical to the attribute’s. Attribute’s setter method Attribute’s getter method DateTag2.java

  26. Invoked when the generated Servlet starts processing the “start tag” public intdoStartTag() throws JspException { try { if (isLongFormat) { pageContext.getOut().print(new java.util.Date().getTime()); } else { pageContext.getOut().print(new java.util.Date()); } } catch (Exception e) { throw new JspException("DateTag: " + e.getMessage()); } return SKIP_BODY; } public intdoEndTag() { return EVAL_PAGE; } } Prints the date according to the isLongFormat attribute Signals the generated Servlet there’s no body within the tag to process Invoked when the generated Servlet starts processing the “end tag” Signals the generated Servlet to continue executing the generated Servlet code

  27. Same as before, only with different names for the tagclass <tag> <name>date2</name> <tagclass>my.DateTag2</tagclass> <body-content>empty</body-content> <attribute> <name>isLongFormat</name> <required>false</required> </attribute> </tag> You can put several blocks one after another 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> <h1>Hello.</h1> <h2>The time is: <mytag:date2/></h2> <h2>Milliseconds since the epoch : <mytag:date2 isLongFormat="true"/></h2> </body></html> Uses default attribute value Uses a given attribute value taglibuse2.jsp

  28. How does it work? taglibuse2.jsp taglibuse2_jsp.java Create the JspContext 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 JspContext JSP to Java Servlet translation DateTag2setIsLongFormat() doStartTag() doEndTag() 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… “Start tag” is reached “End tag” is reached

  29. 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

  30. The Simplified Example date.tag <%=new java.util.Date()%> <%@taglib prefix=“mytag" tagdir="/WEB-INF/tags/"%> <html> <body> <h1>Hello. The time is: <mytag:date/></h1> </body> </html> In this new mechanism we use tagdir instead of uri we used in the old taglib implementation taguse.jsp

  31. A new directive The Attributes Example <%@attribute name="isLongFormat" required="false"%> <%!private String createDate(String isLong) { if ((isLong == null) || (isLong.equals("false"))) { return new java.util.Date().toString();} else { return new Long(new java.util.Date().getTime()).toString();} }%> <%=createDate(isLongFormat)%> date3.tag Private method declaration Default and isLongFormat=“false” case isLongFormat=“true” case Calls the private method The isLongFormat parameter is identified as the isLongFormatattribute because we used the attribute directive <%@taglib prefix=“mytag" tagdir="/WEB-INF/tags/"%> <html><body> <h1>Hello.</h1> <h2>The time is: <mytag:date3/></h2> <h2>Milliseconds since the epoch : <mytag:date3 isLongFormat="true" /></h2> </body></html> Default case isLongFormat=“true” taguse3.jsp

  32. 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

  33. taglib demo

  34. Java Beans in JSP • Custom JSP tags - TagLib • JSP Expression Language Agenda

  35. 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 %>

  36. 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 • param, paramValues, • header ,headerValues, • cookie, • initParam, • pageScope, requestScope, • sessionScope, applicationScope • For example, use the param[“x”] or param.x to get the value of the parameter x Map a parameter name to a single value or to multiple values Map a header name to a single value or to multiple values Maps a cookie name to a single value Maps a context initialization parameter name to a single value

  37. 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!

  38. 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"]

  39. 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> • elcall.jsp

  40. An Example <%@ page isELIgnored="false"%> <html> <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> <h2>Header <code>Connection</code>: ${header.Connection} </h2> <h2>Path of session attr. <code>homepage</code>: ${sessionScope.homepage.path}</h2> <h2>Element <code>arr[${param.x}]</code>: ${arr[param.x]} </h2> </body></html> The default value is TRUE ${…} means evaluate the expression inside the {} cookie[“nameof”].getValue() header [“Connection”] sessionScope[“homepage”].getPath(). You can omit the sessionScope Only the ${param.x} is evaluated sessionScope[“arr”][param[“x”] • el.jsp

More Related