56
1 Struts Tag Library

Struts Tag Library

Embed Size (px)

Citation preview

Page 1: Struts Tag Library

1

Struts Tag Library

Page 2: Struts Tag Library

2

Disclaimer & Acknowledgments● Even though Sang Shin is a full-time employees of Sun Microsystems, the

contents here are created as their own personal endeavor and thus does not reflect any official stance of Sun Microsystems.

● Sun Microsystems is not responsible for any inaccuracies in the contents.● Acknowledgments:

– Struts' user's guide is also used in creating slides and speaker notes– “Using the Struts framework” presentation material from Sue Spielman

of Switchback Software ([email protected])

Page 3: Struts Tag Library

3

Revision History● 11/10/2003: version 1: created by Sang Shin ● Things to do– Speaker notes need to be added to some slides

Page 4: Struts Tag Library

4

Agenda● Struts tag libraries● Struts and JSTL● Struts-EL

Page 5: Struts Tag Library

5

Struts Tag Libraries

Page 6: Struts Tag Library

6

Tag Libraries Overview● Number of taglibs included as part of Struts

– Usage is not required, but helpful● Bean tags

– Tags for accessing Beans and their properties ● Html tags

– Form bridge between JSP view and other components ● Logic tags

– Provides presentation logic tags that eliminate need for scriptlets● Template tags (Tiles in v1.1)

– Tags to form JSP templates that include parameterized content● Nested Tags (v1.1)

– Allows for object hierarchy– Helpful for rendering lists of lists

Page 7: Struts Tag Library

7

Access to Tag Libraries● All tag libraries are defined in web.xml using

<taglib> element

<!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib>

<taglib> <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib>

Page 8: Struts Tag Library

8

Bean Tags

Page 9: Struts Tag Library

9

Bean Tags● Tags for accessing beans and their

properties (not altering, however)● Enhancements to <jsp:useBean>– Some of the attributes, for example id, name,

property, and scope, share same meanings● Convenient mechanisms to create new

beans based on the value of: – User entered parameters– Request headers– Cookies

Page 10: Struts Tag Library

10

Attributes of Bean Tags● id - define a bean● name - refer to an existing bean (the value is

either the value of an id attribute in a previous tag, or is found in application, session, request, or page scope)

● property - a property from a bean● scope - scope to search for the bean. If

scope is not specified then the bean is searched for in page, request, session and application order

Page 11: Struts Tag Library

11

Bean Tags● <bean:define/>● <bean:write/>● <bean:message/>● <bean:include/>● <bean:resource/>● <bean:cookie>● <bean:header>● <bean:parameter>● <bean:size>

Page 12: Struts Tag Library

12

<bean:define/>● For creating variables from beans and

properties– Without it, you would have to create Java code-

based scripting variables in your JSP pages● The variables are used later in the JSP

page● For exposing Java objects (i.e. Collections)

that are created in a Action class to a JSP

Page 13: Struts Tag Library

13

Examples: <bean:define/>● <bean:define id="string" value="Struts in

Javaboutique"/>– Get a bean with a String constant

● <bean:define id="copy" name="dvd"/>– Get an existing bean

● <bean:define id="title" name="copy" property="title"/>– Get a single property from a bean

Page 14: Struts Tag Library

14

Example1: favorites.jsp (ch 03)1 <c:forEach var="theColor" items="${FavoritesForm.colors}" varStatus="loopStatus">2 <bean:define id="ctr">3 <c:out value="${loopStatus.index}"/>4 </bean:define>5 <br/><html:text property='<%="color["+ctr+"]"%>'/>6 </c:forEach>

Page 15: Struts Tag Library

15

Example2: view_favorites.jsp (ch 03)1 <bean:define id="favs" name="FavoritesForm"/>2 <script language="JavaScript">3 function showMessage() {4 alert( "Hello, <bean:write name='favs' property='name'/>!" );5 }6 </script>7 <p>8 Thanks for responding, <bean:write name="favs" property="name"/> !<br/>9 <a href="javascript:showMessage()">Click Me</a>10 </p>11 <p>You have indicated that your favorite colors are:12 <ul>13 <li><bean:write name="favs" property="color[0]"/></li>14 <li><bean:write name="favs" property="color[1]"/></li>15 <li><bean:write name="favs" property="color[2]"/></li>16 </ul>17 <ul>18 <c:forEach var="color" items="${favs.color}">19 <li><c:out value="${color}"/></li>20 </c:forEach>

Page 16: Struts Tag Library

16

Example2: FovoritesForm Class (ch 03)1 public final class FavoritesForm extends ActionForm {2 3 private static String[] javaIdes = new String[] {"Eclipse", "IDEA", "JBuilder", "JDeveloper", "NetBeans"};4 private static String[] csharpIdes = new String[] {"SharpDevelop", "Visual Studio"};5 6 public FavoritesForm() {7 webLinks = new ArrayList();8 for (int i=0; i<5; i++) webLinks.add(new WebLink()); 9 colors = new String[3];10 colors[0]="Black";11 colors[1]="Blue";12 colors[2]="Red";13 }14 ...15 public String[] getColors() {16 return colors;17 }18 public void setColors(String[] colors) {19 this.colors = colors;20 }21 public List getWebLinks() {22 return webLinks;23 }24 public WebLink getWebLink(int index) {25 return (WebLink)webLinks.get(index);26 }27 public void setWebLink(int index, WebLink webLink) {28 webLinks.set(index, webLink);29 }

Page 17: Struts Tag Library

17

<bean:write/>● Use it to output the contents of a bean's

property● The information returned to the page is

rendered as a String● Use it to encode and unencode information

Page 18: Struts Tag Library

18

Example1: <bean:write/><jsp:useBean id="dvd" class="hansen.playground.DVD" scope="request"/>. . .<jsp:getProperty name="dvd" property="title"/>

Using Struts you simply use the write tag:

<bean:write name="dvd" property="title" scope="request"/>

Page 19: Struts Tag Library

19

Example2: submitAction.java1 public final class SubmitAction extends Action {2 3 // The execute() method is where you provide your business logic4 public ActionForward execute(ActionMapping mapping,5 ActionForm form,6 HttpServletRequest request,7 HttpServletResponse response) {8 9 // Cast ActionForm object to SubmitForm type10 SubmitForm f = (SubmitForm) form;11 12 // Retrieve the value of lastname field13 String lastName = f.getLastName();14 15 // Translate the lastname to upper case and save it Request scope16 request.setAttribute("lastName", lastName.toUpperCase());17 18 // Create and return ActionForward object with "success" outcome19 return (mapping.findForward("success"));20 }21 }22

Page 20: Struts Tag Library

20

Example2: submit.jsp1 <logic:present name="lastName" scope="request">2 Hello3 <logic:equal name="submitForm" property="age" value="a">4 young5 </logic:equal>6 <logic:equal name="submitForm" property="age" value="c">7 old8 </logic:equal>9 <bean:write name="lastName" scope="request"/>10 </logic:present>11 12 </body>13 </html>

Page 21: Struts Tag Library

21

Example3: view_favorites.jsp (ch 03)1 <bean:define id="favs" name="FavoritesForm"/>2 <script language="JavaScript">3 function showMessage() {4 alert( "Hello, <bean:write name='favs' property='name'/>!" );5 }6 </script>7 <p>8 Thanks for responding, <bean:write name="favs" property="name"/> !<br/>9 <a href="javascript:showMessage()">Click Me</a>10 </p>11 <p>You have indicated that your favorite colors are:12 <ul>13 <li><bean:write name="favs" property="color[0]"/></li>14 <li><bean:write name="favs" property="color[1]"/></li>15 <li><bean:write name="favs" property="color[2]"/></li>16 </ul>17 <ul>18 <c:forEach var="color" items="${favs.color}">19 <li><c:out value="${color}"/></li>20 </c:forEach>

Page 22: Struts Tag Library

22

<bean:message/>● Looks up a key in the resource file

Page 23: Struts Tag Library

23

Example: index.jsp (ch 03)1 <html:html locale="true">2 <head>3 <title><bean:message key="index.title"/></title>4 <html:base/>5 </head>6 <body bgcolor="white">7 <h2>Struts Chapter 3 Examples</h2>8 9 <p>10 <bean:message key="msg.hello"/>11 </p>

Page 24: Struts Tag Library

24

<bean:parameter/>● Get a request parameter● Example– <bean:parameter id="req" name="item" />

Page 25: Struts Tag Library

25

HTML Tags

Page 26: Struts Tag Library

26

HTML Tags● Form bridge between JSP view and other

components ● Input forms are important for gathering user-

entered data● Most of the actions of the HTML taglib involve

HTML forms● Error messages, hyperlinking,

internationalization

Page 27: Struts Tag Library

27

HTML Tags● checkboxes● hidden fields● password input fields● radio buttons● reset buttons● select lists with embedded option or options items● option● options● submit buttons● text input fields● textareas

Page 28: Struts Tag Library

28

HTML Tags● <html:errors/>● <html:messages/>● <html:html>● <html:form>● <html:link>● <html:text>

Page 29: Struts Tag Library

29

<html:errors/>● Simplest way to display error messages– It is expected that ActionErrors is created (either in

the validate() method of an ActionForm class or in execute() method of an Action class)

● Place the tag anywhere on the page you want the list of errors to be displayed

● Iterates over the errors writing unescaped contents to the page– Messages need to have HTML tags, which are not

desirable

Page 30: Struts Tag Library

30

Example: submit.jsp1 <%@ page language="java" %>2 <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>3 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>4 <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>5 6 <html>7 <head><title>Submit example</title></head>8 <body>9 10 <h3>Example Submit Page</h3>11 12 <html:errors/>13 14 <html:form action="submit.do">15 Last Name: <html:text property="lastName"/><br>16 Address: <html:textarea property="address"/><br>17 Sex: <html:radio property="sex" value="M"/>Male 18 <html:radio property="sex" value="F"/>Female<br>19 Married: <html:checkbox property="married"/><br>20 Age: <html:select property="age">21 <html:option value="a">0-19</html:option>22 <html:option value="b">20-49</html:option>23 <html:option value="c">50-</html:option>24 </html:select><br>25 <html:submit/>26 </html:form>

Page 31: Struts Tag Library

31

Example: ApplicationResources.properties1 errors.header=<h4>Validation Error(s)</h4><ul>2 3 error.lastName=<li>Enter your last name4 error.address=<li>Enter your address5 error.sex=<li>Enter your sex6 error.age=<li>Enter your age7 error.birthYear=<li>Enter the year you were born between 1900 and 2004 inclusive8 9 errors.footer=</ul><hr>

Page 32: Struts Tag Library

32

<html:messages/>● Corrects the problem of <html:errors/>– Allows you to keep HTML tags in JSP pages not in

the resource file● By default, it looks for error messages

stored in the request scope● The id attribute defines the name of the

scripting variable used to expose the error message text

Page 33: Struts Tag Library

33

Logic Tags

Page 34: Struts Tag Library

34

Logic Tags● Provides presentation logic tags that

eliminate need for scriptlets● Value comparisons

Include: = != <= >= < >● Substring matching– match, notmatch

● Presentation logic– forward, redirect

● Collections– iterate

Page 35: Struts Tag Library

35

Logic Tags● <logic:present/>● <logic:equal/>

Page 36: Struts Tag Library

36

<logic:present/> & <logic:notPresent> tags● The body of the <logic:present/> tag is

evaluated whenever the JavaBean, or its property, is present within the JSP page

● Attributes for evaluation– name– parameter– cookie– header– property

Page 37: Struts Tag Library

37

Example: submit.jsp1 <logic:present name="lastName" scope="request">2 Hello3 <logic:equal name="submitForm" property="age" value="a">4 young5 </logic:equal>6 <logic:equal name="submitForm" property="age" value="c">7 old8 </logic:equal>9 <bean:write name="lastName" scope="request"/>10 </logic:present>11 12 </body>13 </html>

Page 38: Struts Tag Library

38

<logic:equal/> & <logic:notEqual> tags● Checks against a specific value in a bean● Assumes the bean exists– Exception occurs if not

● <logic:equal/> tag compares the bean's toString() value aganst the value property

● If property attribute is specified, then the value attribute is compared against the bean's property

Page 39: Struts Tag Library

39

Example: submit.jsp1 <logic:present name="lastName" scope="request">2 Hello3 <logic:equal name="submitForm" property="age" value="a">4 young5 </logic:equal>6 <logic:equal name="submitForm" property="age" value="c">7 old8 </logic:equal>9 <bean:write name="lastName" scope="request"/>10 </logic:present>11 12 </body>13 </html>

Page 40: Struts Tag Library

40

Usage Example: <logic:equal/> & <logic:notEqual> tags● You want to present different messages or

buttons on a page depending upon the type of action you migt perform

● Example:– Depending what a user wants to do (mode) –

view, edit, or delete, you want to present different set of buttons

– View mode: Show only view button– Edit mode: Show view and edit buttons– Delete mode: Show only delete button

Page 41: Struts Tag Library

41

Example: subscription.jsp (ch 13)1 <html:html>2 <head>3 <logic:equal name="SubscriptionForm" property="action"4 scope="request" value="Create">5 <title><bean:message key="subscription.title.create"/></title>6 </logic:equal>7 <logic:equal name="SubscriptionForm" property="action"8 scope="request" value="Delete">9 <title><bean:message key="subscription.title.delete"/></title>10 </logic:equal>11 <logic:equal name="SubscriptionForm" property="action"12 scope="request" value="Edit">13 <title><bean:message key="subscription.title.edit"/></title>14 </logic:equal>15 <html:base/>

Page 42: Struts Tag Library

42

Template Tags

Page 43: Struts Tag Library

43

Template Tags● Templates are JSP pages that include

parameterized content ● Useful for creating dynamic JSP templates

for pages that share a common format● Functionality provided is similar to what

can be achieved using the standard JSP include directive, but these tags allow for dynamic rather than static content

Page 44: Struts Tag Library

44

Template Tags● Three template tags work in an

interrelated function:– Get - Gets the content from request scope

that was put there by a put tag. – Insert - Includes a template– Put - Puts content into request scope

Page 45: Struts Tag Library

45

Template sample (insert/put)

<template:insert template='/layout.jsp'> <template:put name='title'

content='CD Manager Logon‘/> <template:put name='header' content='/header.jsp' /> <template:put name='content‘

content='/logonContent.jsp'/> <template:put name='footer' content='/footer.jsp' />

</template:insert>

Page 46: Struts Tag Library

46

layout.jsp

<html><head> <title> <template:get name='title'/> </title></head> <body > <table> <tr><td> <template:get name='header'/> </td></tr> <tr><td> <template:get name='content'/> </td></tr> <tr><td> <template:get name='footer'/> </td></tr> </table> </body>

</html>

Page 47: Struts Tag Library

47

Struts andJSTL

Page 48: Struts Tag Library

48

When to JSTL in your Struts application?● Developers should evaluate when to use

the JSTL● Many of the Struts taglib features are now

available in the JSTL● It’s simple: If the tag exists in the JSTL –

use it● Continue using the Struts tags where

appropriate, they will continue to be supported

Page 49: Struts Tag Library

49

Interaction with JSTL● Struts-el taglibs allow for using expression

values instead of just rtexprvalueRuntime: <bean:message key='<%= stringvar %>'/>Expression: <bean-el:message key="${stringvar}"/>

● Set of optional taglibs that can be used with the JSTL expression language (EL)

● Implements many (but not all) of the Struts tags.

● Located in the contrib folder of the Struts release

● Container with servlet 2.3 support required

Page 50: Struts Tag Library

50

Struts ELTag library

Page 51: Struts Tag Library

51

Struts EL Extension● Extension of the Struts tag library● Uses the expression evaluation engine in the

Jakarta Taglibs implementation of the JSP Standard Tag Library (version 1.0) to evaluate attribute values

● Some of the Struts tags were not ported to this library– their functionality was entirely supplied by the

JSTL● Requires the use of the Struts tag library, and

the Java Server Pages Standard Tag Library

Page 52: Struts Tag Library

52

Tag Mapping● Every Struts tag that provides a feature that

is not covered by the JSTL (1.0) library is mapped into the Struts-EL library

● Bean Tag Library Tags NOT Implemented in Struts-EL– cookie (in Struts): c:set, EL (in JSTL)– define (in Struts), c:set, EL (In JSTL)

Page 53: Struts Tag Library

53

How to use Struts EL● Struts– <bean:message key='<%= stringvar %>'/>

● Struts EL– <bean-el:message key="${stringvar}"/>

Page 54: Struts Tag Library

54

Best PracticeGuidelines

Page 55: Struts Tag Library

55

Follow Good MVC Practice● JSP pages must “know” as little as possible

about the back-end architecture● JSP page should only concern itself with

rendering the view and not manipulating any data logic

Page 56: Struts Tag Library

56

Passion!