JSTL Slide en

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Java Technologies

Standard Tag Libraries


(JSTL)
The Context
● JSP are used to create the view
● Custom tags are user-defined JSP elements:
– encapsulate functionalities
– promote reusability and role separation
– implemented using
● classes (handlers): by programmers
● JSP → tag files: by designers...
● How can we generate dynamic content in a
tag file without writing Java code ?
The Concept
We need a solution to:

● Allow the designer to implement custom


tags in the form of tag files
● Simplify the creation of JSP pages
– accessing the model (data stored in beans)
– controlling the execution of a page
– etc.
● Standardize the design elements
● Optimize the execution of JSP pages
Example
In a JSP (page or tag file), we verify if the user
has a specific role, using a scriptlet:
<%
User user = (User) session.getAttribute("user");
if (user.getRole().equals("member"))) {
%>

awful...
<p>Welcome, member!</p>
<% } else { %>
<p>Welcome, guest!</p>
<% } %>

It is difficult to provide a custom tag handler for


every situation.
Example (cont.)
A solution more appealing would be:
<c:choose>
<c:when test="${user.role == ’member’}">
<p>Welcome, member!</p>
</c:when> Expression Languge
Standard Tags
<c:otherwise>
<p>Welcome, guest!</p>
</c:otherwise>
</c:choose>
Expression Language (EL)
● Access application data stored in JavaBeans
components
● Create expressions arithmetic and logical in a
intuitive manner:
– ${ (10 % 5 == 0) or ( 2 > 1) ? "yes" : 'no' }
– ${ header["user-agent"] }
● No programming skills required
● Language
– literals, operators, variables, functions
EL Syntax
● Literals: true, false, null, “a”, 'b', 123, 9.99
● Variables
– PageContext.findAttribute(variable)
– page → request → session → application
– variable.property or variable[property]
● Operators: as usual plus:
– eq, ne, ge, le, lt, gt, mod, div, and, or, not, empty
● Implicit Objects:
– param, request, response, session, servletContext
– pageScope, requestScope, sessionScope, applicationScope
– header, cookie, initParam, etc.
Examples
${param[’name’]}
${!empty param.name}
${header["user-agent"]}
${header["host"]}
${initParam.defaultHelloWorldMessage}
${pageContext.request.method}
${pageContext.session.new}
${pageContext.servletContext.serverInfo}
${pageContext.exception.message}
${productMap[category]}
${someArray[0]}
${sessionScope.shoppingCart.items}
EL Custom Functions
● Defined in custom tag libraries
● ${prefix:functionName(param1, param2, …)}
– You have: ${fn:length(shoppingCart.items)} items
– Escape XML tag is: {fn:escapeXml("<table>")}
– <c:if test="${fn:contains(adresa, "Iasi")}">
● In order to create and use a custom function:
– define the function handler (a method in a class)
– map the implementation to a name in the TLD
– use the taglib directive to acces the function
Example of a Custom Function
● The function handler
package somepackage;
public class MyCustomFunctions {
public static String sayHelloTo(String name) {
return "Hello " + name;
}
}
● The TLD
<function>
<name>hello</name>
<function-class>somepackage.MyCustomFunctions</function-class>
<function-signature>
java.lang.String sayHelloTo( java.lang.String )
</function-signature>
</function>
● Using the function
<%@ taglib prefix="f" uri="/WEB-INF/tlds/mylibrary"%>
This is it: ${f:hello("World")}
Standard Tag Libraries (JSTL)
● A collection of useful JSP tags which
encapsulates functionalities common to many
JSP applications.
● JSTL has support for:
– Core Tags
– Formatting tags
– XML tags
– SQL tags
– JSTL Functions
Core Tags (c)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Core tags are the most frequently used JSTL tags.


<c:set var="message" scope="page" value="Hello JSTL!"/>

<c:out value="${message}" default="Hello World!"/>

<c:forEach var="item" items="${sessionScope.cart.items}">


<c:out value="${item}"/> <br/>
</c:forEach>

<c:import url="someFile.csv" var="content" />


<c:forTokens var="item" items="${content}" delims=",">
<c:out value="${item}"/> <br/>
</c:forTokens>

<c:if test="${empty session.user}">


<c:redirect url="login.jsp"/>
</c:if>
Formatting Tags (fmt)
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Used to format and display text, the date, the


time, and numbers for internationalized Web sites.
<jsp:useBean id="now" class="java.util.Date" />
<fmt:setLocale value="ro-RO" />
<fmt:formatDate value="${now}"
type="both"
dateStyle="full" timeStyle="full"/>

<fmt:setLocale value="ro"/>
<fmt:setBundle basename="somepackage.Messages"
var="msg"
scope="page"/>
<fmt:message key="hello"
bundle="${msg}"/>

I18N L10N
Resource Bundles
● Property Files
Messages = basename
Messages_ro.properties
# key-value pairs ro = locale
hello = Salut
bye = La revedere
welcome = Bine ai venit, {0} !
→ /WEB-INF/classes/somepackage

● Classes
package somepackage;
import java.util.*;
public class Messages_ro extends ListResourceBundle {
static final Object[][] contents = {
{"hello", "Salut"},
{"bye", "La revedere"}
};
public Object[][] getContents() {
return contents;
}
}
XML Tags (x)
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

Create and manipulate XML documents: parsing


XML, transforming XML data, and flow control
based on XPath expressions.
<c:import url="agenda.xml" var="xml" />
<x:parse doc="${xml}" var="agenda" scope="application" />
<x:set var="friend"
select="$agenda/friends/person[@id=$param:personId]" />
<x:out select="$friend/name"/></h2>

<x:forEach var="friend"
select="$agenda/friends/person" />
<x:out select="$friend/name" />
</x:forEach>

<c:import url="agenda.xml" var="xml" />


<c:import url="style.xsl" var="style" />
<x:transform source="${xml}" xslt="${style}"/>
SQL Tags (sql)
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

Tags for interacting with relational databases:


connect, read (query), update, delete.
<sql:setDataSource var="timtable"
url="jdbc:sybase:Tds:localhost:2638?ServiceName=TimetableDB"
driver="com.sybase.jdbc4.jdbc.SybDataSource"
user="DBA" password="sql"/>
<sql:setDataSource var="timetabe"
dataSource="jdbc/TimetableDB" />
<c:set var="roomId" value="C401"/>
<sql:query var="rooms" dataSource="${timetable}"
sql="select * from rooms where code = ?" >
<sql:param value="${roomId}" />
</sql:query>
<c:out value="${rooms.rowCount}"/>
<sql:update dataSource="${timetable}">
update rooms set address=’la subsol’ where code=’C112’
</sql:update>
The javax.servlet.jsp.jstl.sql.Result Interface
● Represents the result of a <sql:query> action
that is conform to JavaBeans specifications.
● It provides access to:
– The result rows (getRows() and getRowsByIndex())
– The column names (getColumnNames())
– The number of rows in the result (getRowCount())
– An indication whether the rows returned represent
the complete result or just a subset that is limited by
a maximum row setting (isLimitedByMaxRows())
● Provides a disconnected view into the result of
a query.
Example of using SQL Tags
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<sql:setDataSource var="timetable"
dataSource="jdbc/TimetableDB" />

<sql:transaction dataSource="${timetable}">

<sql:query var="rooms" sql="select * from rooms"/>

<table border="2">
<c:forEach var="colName" begin="0" items="${rooms.columnNames}">
<th><b> <c:out value="${colName}" /> </b></th>
</c:forEach>

<c:forEach var="row" items="${rooms.rows}">


<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column.value}"/></td>
</c:forEach>
</tr>
</c:forEach>

</table>
</sql:transaction>
Standard Functions (fn)
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/fn" %>

Most of then are common string manipulations,


except for <fn:length>
toUpperCase, toLowerCase
substring, substringAfter, substringBefore
trim
replace
indexOf, startsWith, endsWith, contains, containsIgnoreCase
split, join
escapeXml
You bought ${fn:length(shoppingCart.items)} products. Way to go!

<c:if test="${fn:contains(address, "Romania")}">


<%@include file="specialInfoForRomanians.jsp" %>
</c:if>
End of JSP

Let's see some third party alternatives to JSP


Template Engines
● The Context → generate documents
– reports, emails, sql scripts, source files, etc.
– web pages

● We need a generic solution to:


– specify the template
– specify the data
– generate the document
MVC Frameworks

● Template Language → View


● Data (Beans) → Model
● Runtime Engine → Controller
Example: The Template File
Static text + Template Languge (simple syntax)
<html>
<head> <title> Welcome </title> </head>
<body>

<h1>Welcome ${user}!</h1>

<p>Our latest product:


<a href="${latestProduct.url}">${latestProduct.name}</a>!

<p>All the products:


<#list products as product>
<li>${product.name}, ${product.price}

<#if product.stock == 0>


Empty stock!
<#if>

</#list>
</body>
</html>
Example: The Model
(root)
|
+- user = "Big Joe"
|
+- latestProduct
|
+- url = "products/greenmouse.html"
|
+- name = "green mouse"
...

Map<String, Object> data = new HashMap<String,Object>();


User user = new User("Big Joe");
data.put("user", user);

Product product = new Product();


product.setName("green mouse");
product.setUrl("products/greenmouse.html");
data.put("latestProduct", product);

data.put("today", new java.util.Date());


Merging the View and the Model
// Initialization: where are my templates?
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("someFolder"));
// set global variables if you need to
cfg.setSharedVariable("version", "0.0.1 beta");

// Prepare the data


Map<String,Object> data = ... ;

// Choose a template
Template template = cfg.getTemplate("someTemplate.ftl");

// Specify the output stream


String filename = "someFile.html"
Writer out = new BufferedWriter(new FileWriter(filename));

//Do it: process, merge, etc.


template.process(data, out);

out.close();
Using FreeMarker in a Web App
● Register the FreeMarker Servlet
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>
freemarker.ext.servlet.FreemarkerServlet
</servlet-class>
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param> ...
</servlet>
● Map the requests
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
● Any request (.ftl) goes to the servlet
http://localhost:8080/myapp/products.ftl
Other alternatives / ideas...
● Google Web Toolkit
– describe the UI using Swing-like components
– GWT translates all the Java code do JS
● Grails
– uses Groovy instead of Java, high-productivity
framework by following the "coding by convention"
paradigm
● Apache Wicket
– plain Java and HTML, mark-up/logic separation,
POJO data model, a refreshing lack of XML
● ...

You might also like