MELJUN CORTES Jedi course notes web programming-lesson6-advanced js-ps


Published on

MELJUN CORTES Jedi course notes web programming-lesson6-advanced js-ps

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

MELJUN CORTES Jedi course notes web programming-lesson6-advanced js-ps

  1. 1. Advanced JSP IntroductionIn the previous chapter, we have learned about JSPs basic syntax: how to make use ofscriptlets, expressions, JavaBeans, and/or predefined JSP actions to provide dynamicdata along with static content; how to use directives to issue page-specific processinginstructions to the container. We have also outlined JSPs primary role within a webapplication – to serve as its presentation layer, and nothing more.Another point brought up in the previous chapter was JSPs thrust to produce dynamiccontent while keeping programming elements to a minimum. This is to cater todedicated presentation layer personnel who may have little to no experience inprogramming with Java or any other programming language. Shifting to a text-basedformat greatly reduced the lines of code designers had to go through compared toservlets. The contents of the JSP files then became very much alike the standard HTMLthey were used to handling. Refactoring processing logic out of JSPs into servlets andexposing the results as JavaBeans further reduced that amount. At this point though,Java code (through scriptlets) was still an unavoidable element for JSPs. There werefunctionality that simply couldnt be performed by the JSP elements discussed thus far,such as list iteration and logic branching (if-else statements).In this lesson, we will discuss two JSP elements that will reduce the need to includescriptlets and expressions in JSPs to zero. Also, we will present an alternative method ofperforming the functionality that we had previously delegated to scriptlets andexpressions in a format that is simpler and more accessible for personnel with littleprogramming background. JSP Expression LanguageThe first of the two JSP elements that we will explore in this lesson is the JSP ExpressionLanguage (EL). This expression language was introduced with the JSP 2.0 specificationand provides a simple and clean syntax for writing expressions that perform simple logicor access scoped values.The usefulness of JSP EL can best be illustrated with a brief example. Using the methodsdiscussed in the previous lesson, if we wanted to access the property of a JavaBean, wecould have used either:<% String name = user.getLastName(); %>or<jsp:getProperty name="user" property="lastname"/>Using the first method, developers are exposed to Java programming constructs: to
  2. 2. access a beans property, developers have to make use of a beans getter methods. Thedeveloper also needs to be aware of the Java type of the property. The second method ismore programming-neutral: access to the beans property is handled through tags thatare conceptually similar to HTML tags. However, this method of accessing a beansproperty is long and cumbersome. Also, this method presents its output directly to theclient browser; no manipulation can be performed on the retrieved value.Using the EL, the beans property can be accessed as:${user.lastName}The above construct is programming-neutral. The developer does not need to know Javatypes or syntax. It is also short and to the point. The construct contains only the scopedvariable and the property to be accessed, with a minimum of characters added. Also, itcan be used equally for displaying output directly to the user, or to expose the value forcustom tags to process. EL Syntax . LiteralsExpression Language is designed to be simple in its syntax. Basically, an EL constructcan be a literal or an expression enclosed in between ${ and }.EL supports the following literals: • Boolean • Long • Float • String • NullEL literals are treated identically as they are in Java. For example, boolean values caneither be true or false, String values need to be enclosed in either double-quotes ("") orsingle quotes (), and null defines a non-existent value. . OperatorsLiterals by themselves have little functional value within an expression language. Also,EL defines standard operators that can be applied on these literals. The set includes thebasic arithmetic operators (+, -, *, /, %), logical operators (&&, ||, !), and comparisonoperators (==, !=, <, <=, >, >=). . Reserved wordsEL also defines reserved words that mimic the functionality of some of the operators :and (&&), eq (==), gt(>), ge(>=), or (||), ne (!=), le (<=), lt (<), div (/), and mod(%). In addition, the following reserved words are also available: • true – corresponds to the boolean literal value • false - corresponds to the boolean literal value
  3. 3. • instanceof – similar to the Java reserved word. Determines whether an object is child object of a given type. • null – similar to the Java reserved word. Determines a null value. • empty – can be used in multiple ways. When applied on String literals, it determines whether it is a zero-sized String. When applied on literal arrays or on instances of Collection objects, it determines whether it contains any values.The following are examples of EL expressions, given what we have tackled so far:${JEDI} - evaluates to the String JEDI${5 + 37} - evaluates to 42${ (10 % 5) == 2} - evaluates to true${empty } - evaluates to true Accessing Scoped Variables and PropertiesWhile being able to evaluate simple literal expressions is useful, EL shows its importancethe most when accessing and processing variables and properties in different scopes.Variable access is simple with EL: they are simply referenced by name. Bean properties,methods, and arrays can all be accessed from a named variable using the "." notation.This is illustrated by our first example:${user.lastName}This accesses a JavaBean that can be referenced by the name user and retrieves thevalue of its lastName property. Note that the scope of the bean does not matter. ELperforms the scope lookup for us, checking within the page, request, session, andapplication scopes (in that order) for a bean with the specified name. If EL was providedthe name of a bean that does not exist within any scope, a value of null will be returned.Nested methods/properties are accessed the same way. If we want to retrieve the lengthof a users last name, we can first retrieve the lastName property then call on theStrings length method using one call like so:${user.lastName.length} EL Implicit ObjectsWhile automatic scope lookup makes it easier for developers to write code, specifying avariables scope explicitly makes our construct easier to maintain by future developers.EL provides us with several implicit objects that represent a Map of the objects withinthe different scopes as follows. • pageScope • requestScope • sessionScope • applicationScopeFor example, if our earlier User object was located within session scope:
  4. 4. ${sessionScope.user.lastName}Aside from the above, EL also defines the following implicit objects: • param – represents as a Map request parameter names and values. For example invoking ${param.loginName} is equivalent to calling request.getParameter("loginName"). The values stored here are single String values. • paramValues – a Map that maps parameter names to String arrays representing the values for the name. Invoking ${paramValues.choices} is similar to calling request.getParameterValues("choices"). • header – a Map representing the headers available from a given request. Its contents are similar to that retrieved by calling the getHeader method from a ServletRequest object. • headerValues - a Map representing the headers available from a given request. Its contents are similar to that retrieved by calling the getHeaders method from a ServletRequest object. • cookies – maps the cookies available in a request. This is similar to invoking the getCookies method from an HttpServletRequest object. The [] NotationAside from the "." notation, EL also provides the "[]" notation in accessing membervariables, methods, and arrays. In many ways, the two notations are similar. Forinstance, ${user.lastName} is the same as ${user[lastName]}. JSTLThe JSP Expression Language we have outlined above has provided us with a simple andconvenient method of accessing scoped properties and performing simple expressions.However, by itself it does not free us from the use of scriptlets within our JSP pages. Todo so, we turn to custom tags, with the Java Standard Tag Library in particular. Custom TagsOne of the strong points of the JSP specification is that it allows for a degree ofcustomization and extensibility through the use of custom tags. There are alreadyspecialized tags defined within the specification that performs specific tasks: thestandard JSP actions <jsp:useBean>, <jsp:getProperty>, and <jsp:setProperty> areperfect examples. Tags provide a way to expose reusable functionality within a JSP pageusing a very simple interface while hiding the internal implementation. Developers cancreate their own tags so as to provide their own code with this kind of benefit.With this kind of compact reusability (custom tags can be used in any web applicationprovided that the JAR implementations and descriptors are packaged along with the webapp), it would be no wonder that a set of custom tags would be developed byprogrammers and used for various architectural frameworks or custom JSP containers.There are a number of such tag libraries available, and it is unavoidable for them to havesome sort of overlap in the kind of functionality that they provide.
  5. 5. Java has recognized this and, in cooperation with the programming community, hasprovided a standard tag library that addresses the areas of overlap, called the JavaStandard Tag Library or JSTL. Including the JSTL in our ApplicationTo include JSTL functionality in our application, simply unpack the zip file available as adownload, and copy the standard.jar and jstl.jar files located in the /lib directory into the/lib directory of our application.There are several sets of tag libraries packaged under JSTL. Only the core library iscovered in this discussion. Core LibraryThe Core set of tags provide functionality that is useful for any web project. The Core setcan be further sub-categorized into: • General purpose tags • Iteration • Conditionals • URL manipulationNOTE : For every JSP page that will make use of the functionality in the Core tag library,the following directive must be added to the page:<%@taglib uri="" prefix="c" %>This exposes the tags inside the core library using the c prefix. . General Purpose TagsThe general purpose tags in the Core set perform commonplace tasks, though one ofthem has since become irrelevant with the release of the JSP 2.0 specification. The tagscomprising the general purpose set are: out, set, remove, and catch<c:out>The <c:out> tag takes in an EL expression, evaluates its result, and then output theresult directly to the Writer object corresponding to the pages output. This tag functionsmuch the same way as the <jsp:getProperty> standard action, with the exception that aJavaBean is not needed to access the functionality. However, with the release of the JSP2.0 specification, this tag became rather obsolete: EL expressions can be evaluateddirect into the output stream in any part of the JSP page without using any tags with JSP2.0.<c:set>This tag performs much the same functionality as the <jsp:setProperty> action in that itis able to set values within a target JavaBean. It is also able to set a variable within aspecified scope that can be used later by the JSP or elsewhere in the application.
  6. 6. This action has the following attributes: • value – the value that will be set into the target bean. Can be an EL expression. • var – the name of the variable that will be set into a specified scope. • scope – defines the scope of the variable defined by the var attribute. The value can be one of the following: page, request, session, and application • target – the name of the JavaBean whose property will be set. • property – the name of the property within the JavaBean that will receive the value.As has been mentioned before, there are two primary uses for this tag. To set the valuewithin a target JavaBean, the tag makes use of only the value, target, and propertyattributes:<c:set target="user" property="name" value="JEDI"/>The previous call is equivalent to making use of the following JSP expression:<% user.setName("JEDI");%>To set a variable into a defined scope for later use, the <c:set> tag makes use of onlythe value, var, and scope attributes, though the scope attribute is optional. When thescope attribute is omitted, it defaults into using page scope.<c:set var="myString" value="This is a test String" scope="session"/>In the spirit of limiting the JSP for presentation purposes, we should limit the use of thistag. Setting bean properties or setting variables into various scopes is functionality thatcan be refactored elsewhere and are not properly the domain of the presentation layer.<c:remove>This tag provides a way to remove variables from a defined scope. It has two attributes: • scope – the scope of the variable to be removed • var – the name of the variable to be removed from the defined scope.Using this tag to remove the variable set into session scope using the previous <c:set>tag:<c:remove var="myString" scope="session"/>Like the <c:set> tag though, use of this tag should be limited. Freeing up variables fromvarious scopes is not the domain of objects within the presentation layer; this kind offunctionality can be performed elsewhere in the application.<c:catch>The <c:catch> tag provides error handling capability in specific areas in a JSP. It is
  7. 7. simple to use: place the JSP content that could potentially throw errors inside the bodyof the <c:catch> tag.This tag has only one attribute: • var – defines the name that will be used to expose the thrown exception. The variable thus created will have page scope; that is, it is accessible even after the catch block has ended.For example, if we want to handle unexpected runtime errors within our JSP, we coulddo something like this:<c:catch var="exception"> <%-- We force an error here to demonstrate this tags capabilities --%> <% if (true) { throw new Exception("Im an unexpected error"); %></c:catch><%-- The following tag is discussed in more depth later on, in the Conditional section.--%><c:if test="${! empty exception}"> An error has occured in the application : ${exception.message}</c:if> . IterationJSTLs iteration tags provide alternatives to embedding do-while, while, and/or for loopsinside our JSP page as scriptlets. JSTL provides two tags : <forEach> and <forTokens>.<c:forEach>By far, this is the more commonly used iteration tag. It allows iteration over primitivearrays, instances of java.util.Collection, java.util.Iterator, java.util.Map, andjava.util.Enumeration. It does so by going through each element in the target andexposing the current value of the iteration to the JSP code contained inside the tagsbody.This tag has the following attributes: • var – defines the name of the variable used to expose the current value of the iteration to the tag body. Its type is dependent on the collection being iterated over. • items – defines the collection to be iterated over. This can be specified as an EL expression. • varStatus – (Optional). Defines the name of a variable that can be accessed by the loop body to gain information on the current loop status. • begin – (Optional). An int value that defines the index that will be used as the starting point of the iteration. If this value is not supplied, the iteration index starts at 0, the beginning of the collection. Can be a runtime expression. • end – (Optional). An int value that defines the index that determines the stopping
  8. 8. point of the iteration. If no value is specified, the iteration will continue until the last element is reached. • step – (Optional). An int value that defines the step size to be used while going through the iteration. For example, setting this value to two means that only every other element will be accessed and having this at 3 means that elements will be accessed after every 2 elements after the first.A common use of this tag is to iterate over the results of processing performedelsewhere in the application (most likely a servlet). Let us take as an example thefollowing scenario: we have an application module that retrieves from the database userdetails that fall under a specific search category. Naturally, we want to perform thedatabase access logic from a servlet and pass on the data to a JSP for presentation.Below is a code snippet from a servlet that will handle the access:...// load user parameters into a MapMap parameters = loadUserParameters();UserDataService service = new UserDataService();// perform database search, and store the results inside a Collection.Collection results = service.searchUsers(parameters);// store the results for future accessrequest.setAttribute("searchResults", results);// forward the request to a JSP for displayrequest.getRequestDispatcher("/results.jsp").forward(request, response);...Here is a simple JSP page responsible for displaying the results. Let us assume that thecontents of the Collection are instances of a User object which have name and addressas String properties accessible via public get methods.<%@taglib uri="" prefix="c" %><H1>The following users met your search criteria : </H1> <br/><c:forEach var="user" items="${requestScope.searchResults}"> <li> ${} - ${user.address}</c:forEach>In the JSP page, we used the forEach tag to iterate over the search results. We wereable to do this by pointing the forEach tag to the Collection instance stored in requestscope using EL. We then exposed each element in the Collection using the user variablethat we defined in the var attribute, and used EL to display the values.Compare the above to what it would look like without JSTL:
  9. 9. <H1>The following users met your search criteria : </H1> <br/><%Collection results = (Collection) request.getAttribute("searchResults");Iterator iter = results.iterator();while (iter.hasNext()) {User user = (User);%><li> <%= user.getName() %> - <%= user.getAddress() %><%}%>It is obvious that the JSTL-version is a lot more comprehensible, especially to sitedesigners with no knowledge of Java.<c:forTokens>The other iteration tag provided by JSTL is the <forTokens> tag. This tag takes in aString and parses them into tokens based on a given delimiter. All of the attributes ofthe forEach tag are shared by this tag. Aside from those, the following attribute is alsoavailable: • delims – defines the delimiter to be used when parsing the target String into tokens.The items attribute now has a new purpose for this tag. It defines the String that will betokenized.An example is given below:<%@taglib uri="" prefix="c" %>...<c:forTokens items="item1,item2,item3,item4" delims="," var="item"><li> ${item}</c:forTokens> Figure 1: Sample JSPThe previous JSP snippet will result in the following page:
  10. 10. Figure 2: Output of the sample JSP . ConditionalsThe set of tags under this category mimic the funtionality provided by standard if andelse-if statements that can be found in standard Java. Usage of this tags over standardJava statements lead to cleaner code. Having to switch from server-side scripting tonormal HTML output every now and then makes conditionals enabled with scriptletsharder to understand and manage.There are two main sets of conditionals: the <c:if> tag that mimics a simple Java ifstatement; and the <c:choose> tag along with the related tags <c:when> and<c:otherwise>. Altogether, these related tags mimic the functionality of a switchstatement.<c:if>The <c:if> tag allows execution of the contents of its body if the value of the evaluatedexpression in its test attribute is equal to true. If the expression is evaluated to be false,the body is never executed.Sample:<c:if test="${empty sessionScope.user}">You are not currently logged in! Please correct before continuing any further.</c:if><c:choose>, <c:when>, <c:otherwise>These three tags work together to provide switch functionality within our application.Basically, one or more when tags are placed in the body of a choose tag. The choose tagevaluates each of the test attributes of the when tags and executes the body of thewhen tag which evaluates to true. If there are no when tags that successfully match,choose calls on the otherwise tag, if included.Sample:
  11. 11. <c:choose><c:when test="${userGrade >95}">Outstanding!</c:when><c:when test="${userGrade > 80}">Good!</c:when><c:when test="${userGrade < 60}">Failed!</c:when><c:otherwise>Congratulations ...</c:otherwise></c:choose> . URL ManipulationJSTL provides a few custom tags that provide basic URL manipulation capabilities. Thesetags build and improve upon actions already available to JSPs.<c:import>The <c:import> tag works in the same way as the JSP include action, only better. TheJSP include action allowed only pages inside the web application to be referenced andincluded within the current pages content; the <c:import> tag allows developers tospecify absolute URLs pointing to external resources.The attribute to use for this tag is: • url - the value of the URL to import. This can either be a relative URL pointing to a resource within the web application, or an absolute URL pointing to external resources.This tag contains a number of other attributes. However, they are used for programmaticmodification of the contents of the included resource which is something better doneoutside of the JSP. As such, they will not be tackled in this discussion.<c:param>The <c:param> tag is a versatile tag used in conjunction with a number of other tagswithin the URL manipulation group. To emphasize, this tag CANNOT be used on its own,but only as a child tag of other tags available in JSTL. It is used to provide a way toinclude request parameters and values within a URL.The attributes used for this tag are: • name - used to indicate the name of the request parameter. • value - used to indicate the value of the request parameter.The utility of this tag is best illustrated with a brief example. Let us consider the importtag which we have just discussed:
  12. 12. <c:import url="myResource.jsp?username=JEDI Program&location=here"/>If we want to include a dynamic resource that needed values for request parameters, itwould look like the snippet presented above. However, the problem with the aboveexample is that it does not take into account URL encoding rules. There are several rulesfor encoding URLs, one of which is that spaces must be denoted using special characters.The <c:param> tag is able to abstract those encoding rules for us. Instead of worryingabout how to rewrite the URL such that it is compliant with encoding rules, we couldsimply say:<c:import url="myResource.jsp"> <c:param name="username" value="JEDI Program"/> <c:param name="location" value="here"/></c:param><c:url>The <c:url> tag is used to provide a way to automatically reencode a URL with theinformation necessary to support sessions. Remember from our previous discussion onsession management that URL rewriting is one way of supporting sessions if cookies aredisabled.The relevant tag for this attribute is: • value - the URL to be processed.For clarification, this tag does not always reencode the URLs. It ONLY does so when itdetects that the client browser does not support cookies.Below is an example usage of this tag:<HTML> <BODY> Click <a href=" <c:url value="continue.jsp"/> ">here</a> to enter the application. </BODY></HTML>Like the import tag, this tag can have zero to many <c:param> tags for parameterinclusion.EXERCISES1) Assume that a previous component in our web application has placed a Vector intosession scope containing one or more instances of the MenuItem object defined below : public class MenuItem { private String itemName; private String description; private double price;
  13. 13. // getter and setter methods here } Create a JSP page that will retrieve the Vector and iterate over its contents,displaying each of the objects properties. Make use of EL and JSTL in your JSPimplementation.2) Consider the following scenario for the JSP page you are about to create: the pageexpects a parameter named isDebug that returns a value of either true or false. If thevalue of this parameter evaluates to true it displays the following items: - the name of the currently logged user - the userid of the currently logged userAssume that these values are accessible from a User object placed under the propertiesname and userID respectively. The User instance was placed in session scope using thekey "userObject".Regardless of whether or not isDebug is true, the page should show the followingcontent: Thank you for using our application. Unfortunately, the page you requested is stillunder construction.3) Imagine that you have an application that allows its users to browse through a list ofclasses and retrieve its details. A servlet that can be used for performing searches givena parameter named searchKey is already available, and is accessible under the mapping/SearchServlet.What is needed now is a JSP page that will provide users a text box through which asearch key can be entered. If submitted, this form will transfer control to the servletmentioned earlier. Aside from a text box, the page is to provide links labeled from A toZ, which when clicked will submit a request to the servlet, with searchKeys value set tothe letter they represent.Create an implementation of this page, using JSTL and EL, and more importantly,WITHOUT hard-coding each individual link. Big hint: Iterate over a list of letters to avoidhard-coding each one.