1 / 56

Introduction to JSTL

Introduction to JSTL. JSTL is built on a server-side technology called JavaServer Pages (JSP), which in turn is built on top of Java JSP is a powerful template system, but with its power comes complexity.

elsa
Download Presentation

Introduction to JSTL

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. Introduction to JSTL

  2. JSTL is built on a server-side technology called JavaServer Pages (JSP), which in turn is built on top of Java • JSP is a powerful template system, but with its power comes complexity. • JSP, is based on the Java programming language, and it’s hard to use unless you’re a programmer.

  3. Java, JSP, and JSTL

  4. JSTL and other frameworks • JSTL works with JSP versions 1.2 and higher. • JSTL inherits all the benefits from JSP • JSTL will be useful to you whether you use Struts, JavaServer Faces, a different framework, or nothing.

  5. JSTL – A Template System • Web browsers don’t care how web pages are produced. • To a web browser, it makes no difference whether the page it’s displaying is static (unchanging) or dynamic (produced by a programming language or template system) • Template systems like JSP and JSTL are similar to a word-processing feature called mail merge. • In a web template system, template text is mixed with a number of placeholders. • These placeholders are filled in every time the page needs to respond to a web request.

  6. JSP Tags • An interesting subtlety about JSP tags and HTML tags is worth highlighting: • You can use JSP tags inside HTML tags, because these HTML tags are just arbitrary template text. • For instance, you can write: • <a href="<tag:one/>"> • If <tag:one>’s purpose is to print a URL, then this tag might be replaced with <a href="http://your/url "> and it works fine • However, JSP tags cannot appear inside another JSP tag’s attributes. • For instance, if <tag:one> and <tag:two> are both JSP tags, then you can’t write • <tag:one attribute="<tag:two/>"/>

  7. Standard JSP Tags • Some JSP tags are built into JSP; they’re effectively hard-wired into the JSP standard. • These tags are often called standard tags, although the term is somewhat confusing. • This group of “standard” tags doesn’t include JSTL tags; instead, it includes core JSP tags that predate JSTL by several years. • JSTL’s tags are also “standard,” but they fall into a separate group of tags

  8. Standard JSP Tags

  9. Standard JSP Tags • <jsp:include> • Lets you include one JSP page from within another, including the static content • Always looks for files on the local server • Ignores the html’s <base> tag • <jsp:forward> • <jsp:useBean> • Other related tags

  10. JSP Directives • Directives are pseudo-tags that have special meaning to the container; • they are not passed through to the browser but, instead, are processed by the JSP engine • <%@ include %> directive • <%@ page %> directive • <%@ taglib %> directive

  11. <%@ include %> directive • e.g., <%@ include file="b.jsp" %> • Different from <jsp:include> • <%@ include %> directive works by finding the target file and inserting it into your JSP page, just as if you had cut and pasted it using a text editor. • By contrast, <jsp:include> locates the target page while your JSP page is executing. • When page A uses <%@ include %> to include page B, page B’s data is simply included in page A every time it is compiled

  12. <jsp:include> vs. <%@ include%> • If a file included with <%@ include %> changes, its changes will not be noticed until the page containing the directive also changes • page A must be changed—and recompiled —for any changes in B to take effect • <jsp:include> notices changes immediately • <%@ include %> cannot work with Servlets • <%@ include %> is more efficient than <jsp:include>, but it also uses much more disk space when large files are included. • With <jsp:include>, the two pages involved are two entirely separate pages • They can use the same names for different variables, or they can use different prefixes for the same tag library • With <%@ include %>, because page A and page B are essentially merged before being compiled, there might be clashes between names within the two pages

  13. <%@ page %> directive • <%@ page %>, lets you modify some properties of a JSP page • This directive’s goal is to provide meta-information about how to process the page

  14. JSP tag libraries • In contrast with the core JSP tags, other tags can be provided by you, vendors - and, of course, JSTL. • Such tags come in packages called tag libraries • groups of individual tags that are usually designed to work together, or at least to serve a common function. • JSTL is a collection of such tag libraries. • JSTL is distinguished by being the standard tag library— • the one that is found everywhere, • and the one you can learn once and reuse wherever JSP containers are found.

  15. The <%@ taglib %> directive • Tag libraries use prefixes other than jsp, and they must be explicitly imported into pages before they can be used. • Thus, whereas the jsp: tags can be used in any JSP page without fanfare or preparation, you need to introduce others (including JSTL’s) using a special pseudo-tag known as a directive. • Think of JSP directives as being somewhat like the HTML <head> tag • their function is not specifically to display anything in the browser, but instead to describe some information about the page itself.

  16. The <%@ taglib %> directive • Directives are one JSP feature that doesn’t strictly follow an XML-like syntax. • Instead, a directive begins with <%@ and ends with %>. • One such directive, <%@ taglib %>, is used to import a tag library into a page. • Even though they begin with <%@ and end with %>, directives are similar to XML tags in that they accept attributes. • The <%@ taglib %> directive requires two attributes: uri and prefix.

  17. Tag Libraries - URI • Every tag library has something called a Universal Resource Identifier (URI) associated with it. • Not used to load anything over the Web. • It simply acts as a way of differentiating one tag library from another • To use a tag library in a JSP page, you should know its URI • Can be obtained from the author or provider of the library. • If you use JSTL, then the JSTL specification will tell you the appropriate URIs for the JSTL libraries.

  18. Tag Libraries - URI and Prefix • Knowing a library’s URI or file path, you can use the <%@ taglib %> directive to register it and, at the same time, assign it an XML-like namespace prefix for use within the page. • <%@ taglib uri="http://www.acme.com/ custom.tld" prefix="acme" %> • Imports the tag library identified by the URI http://www.acme.com/custom.tld into the page, using the prefix acme. • After this directive appears in a page, tags from the library can be used with the acme prefix. • <acme:create>

  19. JSTL’s tag libraries • JSTL is provided as a collection of tag libraries designed to meet particular needs. • JSTL includes the libraries and recommends certain prefixes • JSTL divides its tags into four groups and makes them available as separate tag libraries. • Core library • XML processing library • Internationalization (i18n) & formatting • Database (SQL) access

  20. Core Library • The core library includes tags for the following uses: • Accessing and modifying data in memory • Making decisions in your pages • Looping over data • Suggested Prefix: c • URI: http://java.sun.com/jstl/core • Example: <c:forEach>

  21. XML processing library • The XML library includes tags for the following purposes: • Parsing (that is, reading) XML documents • Printing parts of XML documents • Making decisions in your page based on the contents of an XML document • Suggested Prefix: x • URI: http://java.sun.com/jstl/jstl/xml • Example: <x:forEach>

  22. Internationalization (i18n) & formatting • The formatting and internationalization library includes tags for these uses: • Reading and printing numbers • Reading and printing dates (with support for time zones) • Helping your application work with more than one language • Suggested Prefix: fmt • URI: http://java.sun.com/jstl/jstl/fmt • Example: <fmt:formatDate>

  23. Database (SQL) access • The SQL library helps you read and write data from databases. • Suggested Prefix: sql • URI: http://java.sun.com/jstl/jstl/sql • Example: <sql:query>

  24. Using JSTL in your pages • Before you can use a tag library, you need to import it. • For each page, you only need to import the libraries you actually use • Core • <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> • XML • <%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %> • Formatting • <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %> • Database • <%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>

  25. JSTL Tag Libraries • JSTL uses a simple language called an expression language to make it easy for you to access information • Before JSTL, you really had to know Java to produce an effective JSP page • JSTL makes writing pages easier. • Its expression language is much simpler than Java; in fact, it’s even simpler than JavaScript.

  26. Expressions and the <c:out> tag • The most fundamental tag • used more often than any other tag in JSTL • Prints the result of an expression • <c:out> tag is a little like JSP’s and ASP’s <%= %> • <c:out value="Hi, there!"/> • prints the text, “Hi there!” • The <c:out> tag becomes useful only when the value attribute contains an expression in JSTL’s expression language • <c:out value="${1 + 2}"/>

  27. JSTL Expressions • In JSTL 1.0, expressions have special meaning only inside JSTL tag attributes • <p>Hi ${username}</p> • Prints as it is • JSTL expressions also have no special meaning inside an HTML tag’s attribute. • <a href="${link}"/> • Meaning-less

  28. <c:out > default attribute • <c:out value="${username}" default="Nobody"/> • <c:out value="${username}"> Nobody </c:out> • <input type="text“ name="username“ value="<c:out value="${param.username}”/>"/>

  29. Accessing Data using JSTL • The major goal of the JSTL expression language is to make data easy to access. • This data can fall into a number of categories • scoped variables, • request parameters

  30. Basic syntax to access scoped variables • In some ways, the JSTL expression language centers on scoped variables • An expression like ${username} simply means “the scoped variable named username.” • When the name of a scoped variable appears alone in an expression, the variable scope is searched in following sequence • page scope, • request, • session, • application

  31. Basic syntax to access scoped variables • ${pageScope.username} • ${requestScope.username} • ${sessionScope.username} • ${applicationScope.username} • <c:out value="${sessionScope.user}"/> • JSTL tags also let you create and store scoped variables

  32. Basic syntax to access scoped variables • ${sessionScope.shoppingCart} • Such a variable refers to an entire collection of objects, organized under a single name: shoppingCart. • ${sessionScope.shoppingCart[0]} • ${sessionScope.user.name} • <c:out value="${sessionScope. shoppingCart[1].price - 10}"/> • ${sessionScope.user["name"]} is equivalent to ${sessionScope.user.name}

  33. Request parameters and the expression language • <c:out value="${param.username}"/> • <p>One language you can read is <c:out value="${param.language}"/></p>

  34. Accessing other data with JSTL • Cookies • If you’re told that a cookie called colorPreference is available, you can access it with an expression like ${cookie.colorPreference} • Headers • Web browsers send information about their make and model to servers using a header called User-Agent • ${header["User-Agent"]} • Initialization parameters • ${initParam.headerUrl}.

  35. Comparisons • You can use expression language to compare values • the expression ${2 == 2} results in true • Every comparison operator has a symbolic version (==) and a textual one (eq)

  36. Expression Language • Checking to see if a variable exists • ${empty param.choice} • ${empty sessionScope.userName} • Multiple Expressions • <c:out value="Hi ${user.first} ${user.last}" />

  37. Saving data with <c:set> • Many JSTL tags let you create scoped variables; the most basic is <c:set> • value • The expression to compute • Required - No • Default - Use body • var • The name of the scoped variable to save • Required - Yes • Default - None • scope • The scope of the variable to save • Required - No • Default - page

  38. <c:set> • <c:set var="four" value="${3 + 1}"/> • <c:set var="four" scope="session" value="${3 + 1}"/> • <c:set var="eight"> <c:out value="${4 * 2}"/> </c:set> • This tag creates a page-scoped variable named eight and sets it to the string 8, which is the result of the <c:out> tag

  39. Deleting data with <c:remove > • <c:remove var="do" scope="session"/> • var • The name of the scoped variable to delete • Required - Yes • Default - None • scope • The scope of the variable to delete • Required - No • Default - Any

  40. JSTL Flow Control • JSTL’s flow control comes in two forms: • Conditional logic, or conditions • Looping, or iteration

  41. JSTL Decisions • Yes-or-no conditions with <c:if> • Mutually exclusive conditions with <c:choose>, <c:when>, and <c:otherwise>

  42. Yes-or-no conditions with <c:if> • test • Condition to evaluate. If true, process the body; if false, ignore the body • Required - Yes • Default - None • var • Name of the attribute to expose a boolean value • Required - No • Default - None • scope • Scope of the attribute to expose a boolean value • Required - No • Default - page

  43. test attribute • The test attribute specifies a conditional expression to evaluate. <c:if test="${user.education == ’doctorate’}"> --do something </c:if> • if the test expression evaluates to false, the page skips the body of the <c:if> tag. • The body can contain any valid JSP code, including text, HTML tags, or other JSP tags <c:if test="${user.education == ’doctorate’}"> Dr. </c:if> <c:out value="${user.name}"/>

  44. <c:if> • <font size="2" <c:if test="${user.education == ’doctorate’}"> color="red“ </c:if> > Hello</font> • <c:if test="${error1}"> Error 1 has occurred </c:if> <c:if test="${error2}"> Error 2 has occurred </c:if> • <c:if test="${error1 or error2}"> <c:if test="${error1}"> Error 1 has occurred </c:if> <c:if test="${error2}"> Error 2 has occurred </c:if> </c:if>

  45. The var and scope attributes • <c:if test="${sessionScope.flags.errors.serious.error1}" var="error1"> -- Saves variable A serious error has occurred. </c:if> [… large page body …] <c:if test="${error1}"> -- Uses variable Since a serious error occurred, your data has not been saved. </c:if>

  46. Mutually exclusive conditions • The <c:choose> tag is simple: • it takes no attributes and serves only as a container for <c:when> and <c:otherwise> tags. • Just as HTML’s <td> tag makes no sense outside a <table>, <c:when> and <c:otherwise> make no sense outside a <c:choose>

  47. Mutually exclusive conditions • <c:choose> <c:when test="${error1}">Error 1 has occurred </c:when> <c:when test="${error2}">Error 2 has occurred </c:when> <c:when test="${error3}">Error 3 has occurred </c:when> </c:choose> • Only one of these <c:when> tags can succeed • <c:choose> <c:when test="${error1}">Error 1 has occurred </c:when> <c:when test="${error2}">Error 2 has occurred </c:when> <c:when test="${error3}">Error 3 has occurred </c:when> <c:otherwise>Everything is fine </c:otherwise> </c:choose> • Addition of <c:otherwise> to display the default message

  48. JSTL Looping • General-purpose looping with <c:forEach> • Iterating over strings with <c:forTokens>

  49. General-purpose looping with <c:forEach> • The basic function of <c:forEach> is to consider every item in the collection specified by its items attribute. • For each item in the collection, the body of the <c:forEach> tag will be processed once, • the current item is exposed as a page-scoped variable whose name is specified by <c:forEach>’s var attribute. • <c:forEach items="${user.medicalConditions}" var="ailment"> <c:out value="${ailment}"/> </c:forEach>

  50. Iterating over strings with <c:forTokens> • A token is a single, discrete unit within a larger string. • The <c:forTokens> tag iterates over tokens, which it parses from an input string • <c:forTokens items="a;b;c;d" delims=";" var="current"> <c:out value="${current}"/> </c:forTokens>

More Related