Java Technologies Standard Tag Libraries (JSTL) The Context JSP - - PowerPoint PPT Presentation

java technologies standard tag libraries jstl
SMART_READER_LITE
LIVE PREVIEW

Java Technologies Standard Tag Libraries (JSTL) The Context JSP - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1

Java Technologies Standard Tag Libraries (JSTL)

slide-2
SLIDE 2

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 ?

slide-3
SLIDE 3

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
slide-4
SLIDE 4

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"))) { %> <p>Welcome, member!</p> <% } else { %> <p>Welcome, guest!</p> <% } %>

It is difficult to provide a custom tag handler for every situation. awful...

slide-5
SLIDE 5

Example (cont.)

A solution more appealing would be:

<c:choose> <c:when test="${user.role == ’member’}"> <p>Welcome, member!</p> </c:when> <c:otherwise> <p>Welcome, guest!</p> </c:otherwise> </c:choose>

Expression Languge Standard Tags

slide-6
SLIDE 6

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

slide-7
SLIDE 7

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.

slide-8
SLIDE 8

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}

slide-9
SLIDE 9

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

slide-10
SLIDE 10

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")}

slide-11
SLIDE 11

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

slide-12
SLIDE 12

Core Tags (c)

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> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

slide-13
SLIDE 13

Formatting Tags (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}"/> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

I18N L10N

slide-14
SLIDE 14

Resource Bundles

  • Property Files

Messages_ro.properties

# key-value pairs 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; } }

Messages = basename ro = locale

slide-15
SLIDE 15

XML Tags (x)

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> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <c:import url="agenda.xml" var="xml" /> <c:import url="style.xsl" var="style" /> <x:transform source="${xml}" xslt="${style}"/>

slide-16
SLIDE 16

SQL Tags (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}"/> <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> <sql:update dataSource="${timetable}"> update rooms set address=’la subsol’ where code=’C112’ </sql:update>

slide-17
SLIDE 17

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.

slide-18
SLIDE 18

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>

slide-19
SLIDE 19

Standard Functions (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> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/fn" %>

slide-20
SLIDE 20

End of JSP

Let's see some third party alternatives to JSP

slide-21
SLIDE 21

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

slide-22
SLIDE 22

MVC Frameworks

  • Template Language → View
  • Data (Beans) → Model
  • Runtime Engine → Controller
slide-23
SLIDE 23

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>

slide-24
SLIDE 24

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());

slide-25
SLIDE 25

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);

  • ut.close();
slide-26
SLIDE 26

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

slide-27
SLIDE 27

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

  • ...