advanced web systems 3- portlet and jsp-jstlunibz.ectrldev.com/awslab13/3-portletandjsp.pdf · 3-...
TRANSCRIPT
Advanced Web Systems 3- Portlet and JSP-JSTL
A. Venturini
Contents
Portlet: doView flow
Handling Render phase
Portlet: processAction flow
Handling the action phase
Portlet URL Generation
JSP and JSTL
Sample: WeatherPortlet
Download from:
http://unibz.ectrldev.com/advanced-web-
systems-course
It is a JSR 168 Portlet compliant
Runs virtually on any portal server
It fully exploits JSR 168 APIs
We use it in this lecture as example, to explain
the typical flows
Weather Portlet Class diagram
Weather Portlet
We assume to have the weather portlet on one
page
The page can contain more portlets
Scenario: show the page
The page should be rendered
The page hosts several portlets
The render method of each portlet is called:
portletMode=VIEW
windowState=NORMAL
ALL THE PORTLETS ARE ASKED TO PRODUCE
THEIR HTML FRAGMENT
NO PROCESS ACTION IS INVOKED, only the
render()
Portal and Portlet Interaction
User Portal Portlet
container
Portlets
A B C
render
render
render
processAction
A
B C
A’
B’ C
Action on B Do action on B
Render A
Render B
Render C
These requests
may be done in
parallel
Scope of the Portlet specification Outside of the scope of the Portlet specification
Weather Portlet Render Sequence Diagram
1. User accesses the page
The get request is managed directly by the portal
server not by your application
The Portal Server, through the Portlet Container,
invoke the render() method
The render() method, superclass of
WeatherPortlet class, invokes the doView method
(portletMode=VIEW and
windowState=NORMAL)
2. Render Method
The portlet has been previously initilized by the
portlet container (at the startup)
The parent class of the portlet (PortletMVC)
dispatch the execution to the jsp configured in
the portlet.xml file, parameter view-jsp
VIEW.JSP
Render the HTML
JSP 1.0:
<%
for (String zip : zips) {
Weather weather =
WeatherUtil.getWeather(zip);
if (weather != null) {
%>
………..
How to generate URL for the portlet
Show data is only one of the things a JSP has to do
Within the HTML generated by the JSP you need to create
links to the application
You cannot use simply (for example):
<a href=“?p1=x&p2=y&p3=z” />
You need to use the Portlet API
Portlet has two type of URL
actionURL: typically for form submission, or url that
changes the application state
renderURL: display one view (also with parameters)
Choosing one or the other is not always obvious
.you can use the portlet taglib in the jsp
<%@ taglib uri="http://java.sun.com/portlet"
prefix="portlet"%>
<portlet:renderURL var="showCityDetailUrl">
<portlet:param name="cityName" value=“bolzano, Italy"/>
<portlet:param name=" desiredView"
value=“showCityDetail"/>
</portlet:renderURL>
<a href="${showCityDetailUrl}"> show info of Bolzano</a>
What is a JSP taglib ?
Is a way to define custom tags
Custom tags are mapped to java classes
implementing a specific interface
These classes can dynamically produce the html
code which will replace the tag itself
Or can set attributes in the request, to be read in
the jsp
When user will click on the link…
The doView method is called:
public void doView(RenderRequest request,RenderResponse
response) throws PortletException,IOException {
String cityName = request.getParameter("cityName");
String desiredView = request.getParameter("desiredView
");
if(desiredView.equals(“showCityDetail”) {
// do the required business logic
// dispatch to a specific jsp (for instance)
}
}
Second scenario
We want to add a link allowing to change the city
to be displayed
Or using the taglib
<%@ taglib uri="http://java.sun.com/portlet"
prefix="portlet"%>
<portlet:actionURL var="setCityNameUrl">
<portlet:param name="cityName"
value=“bolzano, Italy"/> <portlet:param name="
desiredView" value=“setCityName"/>
</portlet:actionURL>
<a href="${setCityNameUrl}"> switch to the
weather in Bolzano</a>
ProcessAction flow
When user will click on the link…
The processAction method is called:
public void processAction(ActionRequest request,
ActionResponse response) {
PortletPreferences pref = request.getPreferences();
String cityName = request.getParameter("cityName");
pref.setValue("cityName", cityName);
pref.store();
}
Remarks
The ProcessAction reads parameters and sets the
new parameters in the configuration
The render method has dispatched to the JSP
The JSP has “just” to format and build the html
The JSP does not do any business logic, does not
change the application state
This is an example of Model View Controller
pattern
Remarks
The JSP is invoked by the portlet class (via
include())
MODEL 2 approach
“Models” of JSP development
Origin of the terms “model 1” and
“model 2.”
JSP 0.92 spec: “You can apply the JavaServer
Pages technology in two ways . . . Model 1: A request sent
to a JavaServer Pages file. . . . Model 2: A request sent to
a Java Servlet.”
Simple “model 2” example public void doGet(HttpServletRequest request
HttpServletResponse response) {
// business logic that results in object ’data’
request.setAttribute(”d”, data);
sc.getRequestDispatcher(”/view.jsp”);
}
view.jsp
We have some data to display: <b>${d.property1}</b>
• In this case, the data passed is a simple bean-style object. It could also be an XML document; we’d then use JSTL’s XML-manipulation tags.
JSP and JST 2.0
Some tutorial:
Author of next slides is:
Shawn Bayern, Research Programmer, Yale University
http://www.ibm.com/developerworks/java/library/j-jstl0211.html
http://www.ibm.com/developerworks/java/library/j-jstl0318/
J2EE presentation tier
Servlets Java classes that handle requests by producing
responses (e.g., HTTP requests and responses)
(Portlets are invoked by Portal server servlets!)
JavaServer Pages (JSP) HTML-like pages with some dynamic content.
They turn into servlets automatically.
JSP Standard Tag Library (JSTL) Set of standard components for JSP.
It is used inside JSP pages.
Organization of the platform
Your application
Java language
Java Servlet API
JavaServer Pages (JSP)
JSTL
Your web pages
What kinds of things go in JSP pages?
Scriptlets
<%
getFoo(request);
printFoo(out);
String a = ”italy”;
%>
<% if (a.equals(”italy”)
{%>
<img src=“italy.png/>
<% } %>
Java (and more?) embedded within template text
Access to implicit objects: request, response, etc.
Conditional blocks, loops—manually constructed
What kinds of things go in JSP pages?
Tag libraries
<foo:bar/>
<c:if test=”${c}”>
c is true
</c:if>
<c:forEach var=”i”
items=”${items}”>
loop
</c:forEach>
XML tags
Invoke Java logic behind the scenes.
May access body, e.g., for iteration, conditional inclusion—or just as arbitrary parameter
May access PageContext
Libraries and prefixes
Extension introduced with JSP 2.0
Expression language
Tag files
Simplified Tag API (SimpleTag versus Tag)
Also, though it’s not really part of JSP,
JSTL improves things too.
The end result:
JSP pages become easier to write and maintain.
The JSP Expression Language (EL): Key syntax
Expressions appear between ${ and }.
Note that ${ and } may contain whole expressions, not just variable names, as in the Bourne shell (and its dozen derivatives.)
E.g., ${myExpression + 2}
Expressions’ default targets are scoped attributes (page, request, session, application) ${city} ≡ pageContext.findAttribute(“city”)
The JSP Expression Language (EL): Key syntax
The . and [] operators refer to JavaBean-style properties and Map elements:
${city.cityName} can resolve to ((City) pageContext.getAttribute(”city”)).getCityName()
Note the automatic type-cast. This is one of the great features of the EL: users do
not need to concern themselves with types in most cases (even though the underlying types of data objects are preserved.)
The JSP Expression Language (EL): advanced data access
Expressions may also refer to cookies, request
parameters, and other data:
${cookie.crumb}
${param.password}
${header[“User-Agent”]}
${pageContext.request.remoteUser}
The JSP Expression Language (EL): more syntax
The EL supports
Arithmetic ${age + 3}
Comparisons ${age > 21}
Equality checks ${age = 55}
Logical operations ${city=‘bolzano’ or city=‘trento’}
Emptiness detection ${empty a}
‘a’ is empty String (“”), empty List, null, etc.
Useful for ${empty param.x}
The JSP Expression Language: Uses
JSTL 1.0 introduced the EL, but it could be used only within tags.
In JSP 2.0, it can be used almost anywhere
<font color=”${color}”>
Hi, ${user}.
You are <user:age style=”${style}”/> years
old.
</font>
Tag Files: nature and purpose
Solve difficulty of reusing text/HTML within a tag.
And makes it much easier to write simple tags,
since you can do so in JSP instead of Java.
Stand-alone file with <%@ tag %>
directive instead of traditional
<%@ page %> directive.
JSP 2.0 tag files
<%@ tag name=”tableTag” %>
<%@ attribute name=”items” %>
<table width=”…” bgcolor=”…”>
<th>
<td>Name</td>
<td>Age</td>
</th>
<c:forEach var=”i” items=”${items}”>
<tr>
<td>${i.fullName}</td>
<td>${i.age}</td>
</tr>
</c:forEach>
</table>
Using the new tag…
Your shopping cart:
<my:tableTag items=”${cart}” />
Your wish list:
<my:tableTag items=”${wishList}” />
Things we want you to buy:
<my:tableTag items=”${pressuredSales}” />
Old tag handler
Tag handler
doStartTag() doEndTag()
doCatch() doFinally()
Tag attributes
Tag body
doInitBody()
doAfterBody()
release()
SimpleTag handler
Tag handler
Tag attributes
Tag body (no scriptlets)
doTag()
USER GENERATED TAG FUNCTION (1)
package mytaglib;
public class MyFunctions
{
public static boolean contains(java.util.Set<String> set, String
target)
{
return set.contains(target);
}
}
USER GENERATED TAG FUNCTION (2)
WEB-INF/MyTags.tld
<?xml version="1.0" encoding="UTF-8"?> <taglib version="2.0"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee web-
jsptaglibrary_2_0.xsd">
<tlib-version>1.1</tlib-version>
<uri>/WEB-INF/MyTags</uri>
<function>
<name>contains</name>
<function-class>mytaglib.MyFunctions</function-class>
<function-signature> boolean contains(java.util.Set,java.lang.String)
</function-signature>
</function>
</taglib>
USER GENERATED TAG FUNCTION (3)
In the JSP you can use:
<%@taglib prefix="mtg" uri="/WEB-INF/MyTags"%>
<c:if test="${mtg:contains(someSet,someValue)}" > ...
</c:if>
JSTL 1.0 features
Control flow
Iteration, conditions
URL management
Retrieve data, add session IDs
Text formatting and internationalization
Dates and numbers
Localized messages
XML manipulation
XPath, XSLT
Database access
Queries, updates
JSTL 1.0 libraries
Library features Recommended prefix
Core (control flow,
URLs, variable access)
c
Text formatting fmt
XML manipulation x
Database access sql
JSTL TAGS
c:
<%@taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
fn:
<%@taglib prefix="fn"
uri="http://java.sun.com/jsp/jstl/functions" %>
fmt:
<%@taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
xml:
<%@taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
JSTL features: managing variables
Outputting values with EL
<c:out value=”${user.age}” />
Storing data
<c:set var=”user”
scope=”session”>
// arbitrary text
</c:set>
Note the use of “var” and “scope”: a JSTL convention
JSTL features: iteration
Iteration
<c:forEach items=”${list}”
begin=”5” end=”20” step=”4”
var=”item”>
<c:out value=”${item}”/>
</c:forEach>
“paging”
Iteration (2)
Iterating over a list:
<!-- L represents either an array, list or set -->
<c:forEach var="x" items="${L}" >
${x}
</c:forEach>
Iterating over a map:
<!-- M is a map -->
<c:forEach var="x" items="${M}" >
${x.key}: ${x.value}
</c:forEach>
JSTL features: conditional logic
Conditional evaluation
<c:if test=”${a == b}”>
a equals b
</c:if>
Mutually exclusive conditionals
<c:choose>
<c:when test=”${a == b}”>
a equals b
</c:when>
<c:when test=”${a == c}”>
a equals c
</c:when>
<c:otherwise>
I don’t know what ’a’ equals.
</c:otherwise>
</c:choose>
JSTL features: URL management
Retrieving data
<c:import var=”cnn”
url=”http://www.cnn.com/cnn.rss”/>
Data exposed as String or Reader
All core URLs supported (HTTP, FTP, HTTPS with JSSE)
Local, cross-context imports supported
Printing URLs
<c:url value=”/foo.jsp”>
Redirection
<c:redirect url=”/foo.jsp”>
JSTL features: text formatting
Locale-sensitive formatting and parsing
Numbers
Dates
Internationalization
Message bundles
Message argument substitution
“Hi {0}. Your cart is {1} .”
<fmt:formatNumber type=“currency” value=“${salary}” />
<fmt:message key=“welcome” />
JSTL features: XML manipulation
Use of XPath to access, display pieces of XML documents
<c:import url=”http://www.cnn.com/cnn.rss” var=”cnn”/>
<x:parse xml=”${cnn}” var=“dom”>
<x:out value=”$dom//item[1]/title”/>
Chaining XSLT transformations
<x:transform xslt=”${xsl2}” />
<x:transform xml=”${xml}” xslt=”${xsl}” />
</x:transform>
JSTL features: database manipulation (BUT DO NOT USE THEM!)
Queries (and ResultSet caching)
Updates / inserts
Transactions (<sql:transaction>)
Parametric (PreparedStatement) argument substitution (<sql:param>)
DataSource-based connection management
<sql:query sql=“SELECT * FROM USERS” var=“result” />
<c:forEach items=“${result.rows}”> … </c:forEach>
SQL tags: the debate
Tag library
JSP page
Back-end Java code
Database
Tag library
SQL Tags: The expert group’s conclusion
SQL tags are needed because…
many nonstandard offerings exist
it is not JSTL’s role to dictate a choice of framework As popular as MVC is, it’s not universal.
Even in an MVC application, not all data is worth handling carefully.
prototyping is important
users ask for it!
The JSTL specification recommends avoidance of SQL tags in large applications.
Examples: a select allowing to choose a date among a set of dates
In the included jsp:
<select name=“dates">
<c:forEach items="${datesColl}" var=‘dateoption'>
<option value="${dateoption}" ${dateoption ==selectedDate
? 'selected' : ''}>${dateoption}</option>
</c:forEach>
</select>
In the doView method: List<String> datesColl = new ArrayList(); datesColl.add("12/02/2009"); datesColl.add("13/02/2009"); renderRequest.setAttribute("datesColl", datesColl); renderRequest.setAttribute("selectedDate", "13/12/2009");
Examples: a list of maps
In the included jsp:
<c:forEach items="${weeklylist}" var="mapItems" varStatus="listStatus">
<c:out value="Day "/><c:out value="${listStatus.count}"/><br>
<c:forEach items="${mapItems}" var="mapIter">
<div class="list_item">
<a href> ${mapIter.value.itemName} </a><br>
</div>
</c:forEach>
</c:forEach>
In the doView method: List<Map<String, Item>> weeklyList =getWeeklyData(); renderRequest.setAttribute("weeklylist", weeklyList);
Questions ?