Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
As J2EE programmers, we are familiar with Servlets , JSP and JavaBeans. Any JSP page should encapsulate the business logic in a bean and invoke it by using <jsp:useBean> tag. Till recently, a combination of Servlets, JSP and beans was the standard practice. But, the JCP released an API for enabling programmers to create custom tags and use them in their JSP pages. The difference between javabean and java custom tags was that, though both made use of java classes, tags can be used by non-programmers also without knowledge of Java programming, just as they would use html tags.( From a programmer's perspective,however, a much more important distinction is that tags are specific to the page in which they are created while javabeans are general. )
// greeting.htm =============
<html> <body>
<form method=post action= 'http://localhost:8080/servlet/greeting'> <input type=text name='text1'> <input type=submit> </form> </body> </html>
(relevant section of greeting.java servlet) // greeting.java ( code-snippet only) public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); //------------------------------String s = req.getParameter("text1"); out.println("<html><body bgcolor=yellow>"); out.println("we welcome"+",<br>"); out.println (s); out.println("</body> </html>"); }
// greeting1.jsp <html> <body bgcolor=yellow> <% String s = request.getParameter("text1"); out.println("we welcome"+<br>); out.println(s); %> </body> </html>
---------------------------------------------// greeting2.jsp <html> <body bgcolor=yellow> we welcome <br> <%= request.getParameter("text1") %> </body> </html>
// greeter.java //============== package ourbeans; public class greeter { public greeter() { } public String greetme(String s) return "we welcome..."+s; } }
/ greeting3.jsp <html> <body> <jsp:useBean id='bean1' class='ourbeans.greeter'> <% String s = request.getParameter ("text1"); String r = bean1.greeteme(s); out.println(r); %> </body> </html>
// greeting4.jsp ( uses JSTL) =========== <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body> <c:set var=s value="${param.text1}" /> We welcome<br> <c:out value="${s}" /> </body> </html>
There are five groups under which the JSTL tags have been organized. They are as follows: 1) core 2) xml 3) sql 4) formatting 5) functions.
Web browsers dont care how web pages are produced. To a web browser, it makes no difference whether the page its 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.
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 tags attributes. For instance, if <tag:one> and <tag:two> are both JSP tags, then you cant write
<tag:one attribute="<tag:two/>"/>
Some JSP tags are built into JSP; theyre 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 doesnt include JSTL tags; instead, it includes core JSP tags that predate JSTL by several years. JSTLs tags are also standard, but they fall into a separate group of 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 htmls <base> tag
<jsp:forward> <jsp:useBean>
JSP Directives
they are not passed through to the browser but, instead, are processed by the JSP engine <%@ include %> directive <%@ page %> directive <%@ taglib %> 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 Bs data is simply included in page A every time it is compiled
If a file included with <%@ include %> changes, its changes will not be noticed until the page containing the directive also changes
<%@ 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
page A must be changedand recompiled for any changes in B to take effect <jsp:include> notices changes immediately
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
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.
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 JSTLs) 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.
Directives are one JSP feature that doesnt 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.
Every tag library has something called a Universal Resource Identifier (URI) associated with it.
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.
Knowing a librarys 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>
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
Core Library
Accessing and modifying data in memory Making decisions in your pages Looping over data
Parsing (that is, reading) XML documents Printing parts of XML documents Making decisions in your page based on the contents of an XML document
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
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
XML
Formatting
Database
Prints the result of an expression <c:out> tag is a little like JSPs and ASPs <%= %> <c:out value="Hi, there!"/>
The <c:out> tag becomes useful only when the value attribute contains an expression in JSTLs expression language <c:out value="${1 + 2}"/>
JSTL Expressions
In JSTL 1.0, expressions have special meaning only inside JSTL tag attributes
JSTL expressions also have no special meaning inside an HTML tags attribute.
Nobody
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
JSTL tags also let you create and store scoped variables
${sessionScope.shoppingCart}
Such a variable refers to an entire collection of objects, organized under a single name: shoppingCart.
Cookies
If youre told that a cookie called colorPreference is available, you can access it with an expression like ${cookie.colorPreference} Web browsers send information about their make and model to servers using a header called User-Agent
Headers
${header["User-Agent"]}
Initialization parameters
${initParam.headerUrl}.
Comparisons
Every comparison operator has a symbolic version (==) and a textual one (eq)
Expression Language
Multiple Expressions
Many JSTL tags let you create scoped variables; the most basic is <c:set> value
var
scope
The name of the scoped variable to save Required - Yes Default - None The scope of the variable to save Required - No Default - page
<c:set>
<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
The name of the scoped variable to delete Required - Yes Default - None The scope of the variable to delete Required - No Default - Any
scope
JSTL Decisions
Yes-or-no conditions with <c:if> Mutually exclusive conditions with <c:choose>, <c:when>, and <c:otherwise>
test
Condition to evaluate. If true, process the body; if false, ignore the body Required - Yes Default - None
Name of the attribute to expose a boolean value Required - No Default - None Scope of the attribute to expose a boolean value Required - No Default - page
var
scope
test attribute
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}"/>
<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>
<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>
it takes no attributes and serves only as a container for <c:when> and <c:otherwise> tags. Just as HTMLs <td> tag makes no sense outside a <table>, <c:when> and <c:otherwise> make no sense outside a <c:choose>
<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>
<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>
JSTL Looping
General-purpose looping with <c:forEach> Iterating over strings with <c:forTokens>
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:forTokens items="a,b,c,d,e,f" delims="," var="letter begin="4"> <c:out value="${letter}"/> </c:forTokens> This invocation of the tag will print out only the letters e and f. Similarly, we can use only end:
<c:forTokens items="a,b,c,d,e,f" delims="," var="letter" end="4"> <c:out value="${letter}"/> </c:forTokens> This tag outputs a, b, c, d, and e, but not f, because the index of e in this collection is 4.
<sql:setDataSource driver="org.hsqldb.jdbcDriver url="jdbc:hsqldb:. user="sa password="donkey scope="session" /> The <sql:setDataSource> tag does not support connection pooling. <sql:query var="result" sql="SELECT * FROM CUSTOMERS"/> <sql:query var="smartUsers"> SELECT NAME, IQ FROM USERS WHERE IQ > 120 </sql:query> <table> <c:forEach items="${smartUsers.rows}" var="row"> <tr> <td><c:out value="${row.NAME}"/></td> <td><c:out value="${row.IQ}"/></td> </tr> </c:forEach> </table>
<sql:update> INSERT INTO PEOPLE(NAME, AGE, WEIGHT) VALUES(John "Fatso" Smith, 34, 540) </sql:update> <sql:update var="n"> DELETE FROM CUSTOMERS WHERE AGE < 18 </sql:update> <p>Our CUSTOMERS table had <c:out value="${n}"/> minors. They have all been removed. Close call; were lucky the Feds didnt come after us.</p>
<sql:query> SELECT * FROM USERS WHERE BIRTHDAY < ? <sql:dateParam value="${myBirthday}"/> </sql:query>
JSTL in Action
With this, you have covered approx. 8 chapters of the book JSTL in Action (Manning) For additional insight please refer the book Read Chapter 10 of the book regarding formatting & internationalization its interesting