Using Struts HTML Tags to Render Basic HTML Elements


This section provides information about the following tags:

  • <html:html> ” Render an HTML <html> element

  • <html:base> ” Render an HTML <base> element

  • <html:link> ” Render an HTML Anchor tag <a> element

  • <html:rewrite> ” Render only the URI portion of a <html:link> tag

  • <html:img> ” Render an HTML <img> element

If you point your browser to the URL

 http://myAppServer/StrutsTaglibs/html.jsp 

you'll bring up the main page linking to all the sample code for the Struts tag chapters. This section uses the HTML Basics page at /StrutsTaglibs/HtmlBasic.do . The rendered page is shown in Figure 12.2.

Figure 12.2. The HTML Basics page at /StrutsTaglibs/HtmlBasic.do .

graphics/12fig02.gif

As you can see from the figure, this page has no forms or Submit buttons . Listing 12.1 is the JSP file that creates this page.

Listing 12.1 JSP File Demonstrating Usage of Struts HTML Tags That Generate Basic HTML Tags (Not FORM - Related ) ( HtmlBasic.jsp )
 <%@ page language="java"%> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <html:html> <head> <title>Base HTML Tags</title> <html:base/> </head> <body bgcolor="white"> <h3>Sample code for basic Struts html tags</h3> <p>This page provides examples of the following Struts HTML tags:<br> <ul> <li>&lt;html:html&gt;</li> <li>&lt;html:base&gt;</li> <li>&lt;html:link&gt;</li> <li>&lt;html:rewrite&gt;</li> <li>&lt;html:img&gt;</li> </ul> <table border="1" width="100%">   <tr>     <th colspan="3" align="left">       Sample &lt;html:link&gt; tags     </th>   </tr>   <%--   The following section contains three <html:link> tags. Each   demonstrates a different way of creating an anchor tag (<a href=...>).   --%>   <tr>     <td align="left">       <%-- Create link from a Global Forward in the struts-config.xml --%>             <html:link forward="index">         Link to Global ActionForward       </html:link>     </td>     <td align="left">       <%-- Create link by specifying a full URL --%>       <html:link href="http://jakarta.apache.org/struts/index.html">         Generate an "href" directly       </html:link>     </td>     <td align="left">       <%-- Create the link as a relative link from this page --%>       <html:link page="/HtmlBasic.do">         A relative link from this page       </html:link>     </td>   </tr>   <%--   The <html:link> and <html:rewrite> tags a very similar. The only difference   is that <html:rewrite> creates the URI without prepending the   "http://hostname:port/" part.   --%>   <tr>     <%-- Create link and hard-code request parameters --%>     <td colspan="1" align="left">       <html:link page="/HtmlBasic.do?prop1=abc&amp;prop2=123">         Hard-code the url parameters       </html:link>     </td>     <%-- Create the same rewrite string for the above link. --%>     <td colspan="2" align="left">       <b>rewrite: </b>       <html:rewrite page="/HtmlBasic.do?prop1=abc&amp;prop2=123" />     </td>   </tr> <%   /*    * Create a String object to store as a bean in    * the page context and embed in this link    */   String beanName = "Value to Pass on URL";   pageContext.setAttribute("pageAttribute1", beanName); %>   <tr>     <%-- Create link with request parameters from a bean --%>     <td colspan="1" align="left">       <%-- For this version of the <html:link> tag:                    --%>       <%--   paramID = the name of the url parameter                   --%>       <%--   paraName = the "attribute" for the bean holding the value --%>       <html:link page="/HtmlBasic.do"               paramId="urlParamName" paramName="pageAttribute1">       URL encode a parameter based on a bean value       </html:link>     </td>     <%-- Create the same rewrite string for the above link. --%>     <td colspan="2" align="left">       <b>rewrite: </b>       <html:rewrite page="/HtmlBasic.do"               paramId="urlParamName" paramName="pageAttribute1" />     </td>   </tr> <%    /*     * Store values in a Map (HashMap in this case)     * and construct the URL based on the Map     */   java.util.HashMap myMap = new java.util.HashMap();   myMap.put("myString", new String("myStringValue") );   myMap.put("myArray", new String[] { "str1", "str2", "str3" });   pageContext.setAttribute("map", myMap); %>  <tr>     <%-- Create a link with request parameters from a Map --%>     <td colspan="1" align="left">       <%-- For this version of the <html:link> tag: --%>       <%--   map = a map with name/value pairs to pass on the url --%>       <html:link page="/HtmlBasic.do" name="map">       URL encode a parameter based on values in a Map       </html:link>     </td>     <%-- Create the same rewrite string for the above link. --%>     <td colspan="2" align="left">       <b>rewrite: </b>       <html:rewrite page="/HtmlBasic.do" name="map"/>     </td>   </tr> </table> <table border="1" width="100%">   <tr>     <th colspan="3" align="left">       Sample &lt;html:img&gt; tags     </th>   </tr>   <tr>     <%-- Create a default <img> tag --%>     <td align="center">       <html:img page="/struts-power.gif" />     </td>     <%-- Create an <img> tag with request parameters from a bean --%>     <td align="center">       <%-- Note "src" requires using full relative path --%>       <html:img src="/StrutsTaglibs/struts-power.gif"                      paramId="urlParamName" paramName="pageAttribute1" />     </td>     <%-- Create an <img> tag with request parameters from a map --%>     <td align="center">       <html:img page="/struts-power.gif" name="map" />     </td>   </tr> </table> </html:html> 

The following sections outline the functionality related to the tags demonstrated in the preceding listing.

The <html:html> Tag

The <html:html> tag simply generates the <html> HTML element at the beginning of the file. In our case, this is a very basic tag.

If this application were written to provide locale-specific text, the tag could have been written as

 <html:html locale="true"> 

Using the local="true" option causes this page to set its locale value based on the Accept-Language header submitted by the client browser (if a locale was not already set).

The <html:base> Tag

The <html:base> tag generates an HTML <base> element in the <head> section of the document. The <base> HTML element is used to assist the client browser in correctly forming relative URL paths if they're present in the HTML page.

In this case, our <html:base/> tag rendered the following HTML:

 <base href="http://localhost:8080/StrutsTaglibs/HtmlBasic.jsp"> 

For more information about this tag, please refer to an appropriate HTML reference guide.

The <html:link> and <html:rewrite> Tags

The <html:link> tag is the tag used to generate anchor tags, or hyperlinks . It's a very useful tag that you'll use a great deal if you need to build your application either to

  • Pass parameters on the URL (as opposed to submitting them all from forms)

  • Maintain session state with users who have cookies turned off

Because it's very likely that one conditions of these is true, you should plan to create hyperlinks using the <html:link> tag rather than by directly creating hyperlinks without it.

The <html:rewrite> is very similar to the <html:link> tag. The only difference between them is that the <html:rewrite> tag creates only the URI portion of the hyperlink.

The URI portion of a Web address is that part that comes after the protocol, host, and port are specified for the request. The URI simply defines the resource being requested . For example, given the URL http://localhost:8080/StrutsTaglibs/HtmlBasic.do , the URI part is /StrutsTaglibs/HtmlBasic.do .

For example, the <html:rewrite> tag can be useful if you need to pass the URI of a resource into a JavaScript function.

URL ENCODING VERSUS FORM POSTING

There are two ways that parameters get passed from a user request in the client browser into your application running on the server: posting them via a form or encoding them in the request URL.

URL encoding refers to literally embedding name/value pairs directly into the URL that the client browser requests . For example, the client browser may issue an HTTP GET command for the resource /myApp/myFile.jsp?var1=abc&var2=def .

In this situation, the server passes the request parameters var1 and var2 to the application with the values abc and def , respectively.

In URL encoding, parameters are visible in the URL address section of the client's browser. It's also possible that a user might manually change parameters in the request and then refresh the browser to reexecute a request ”this could potentially pose a security threat.

In form posting, parameters are posted to the server using the HTTP POST method. This has the security advantage of not making the parameters visible in the URL.

That being said, there are good reasons to use URL encoding. Sometimes building hyperlinks with parameters embedded in them is a good way to pass information into a page when it doesn't make sense to use a form. Also, if a user has cookies disabled, you might not be able to store Session IDs or other information in a cookie on the user's browser.

The <html:link> tag provides convenience and a great deal of flexibility if it makes sense for your application to URL encode request parameters. It also automatically handles URL encoding of Session IDs to ensure that you can maintain session state with users who have cookies turned off in their browser.

The following sections describe the various ways our sample application uses the <html:link> tag.

Create Link from a Global Forward in the strutsconfig.xml

First, define a global forward in the struts-config.xml file similar to:

 <global-forwards>     <forward   name="index" path="/index.jsp"/>   </global-forwards> 

Next, create the <html:link> tag in the JSP file:

 <html:link forward="index">   Link to Global ActionForward </html:link> 

The HTML generated is

 <a href="/StrutsTaglibs/index.jsp">Link to Global ActionForward</a> 

Be careful that you only use <forward> s that are defined as <global-forwards> . If you reference a <forward> defined down in the <action> section of your strutsconfig.xml file, you'll throw an exception similar to the following:

 Cannot create rewrite URL: Java.net.MalformedURLException: Cannot retrieve ActionForward 
Create Link by Specifying a Full URL

This is the best way to generate hyperlinks to sites outside your application. Simply use the href attribute of the <html:link> tag in a way similar to the following:

 <html:link href="http://jakarta.apache.org/struts/index.html">   Generate an "href" directly </html:link> 

The HTML generated is

 <a href="http://jakarta.apache.org/struts/index.html"> Generate an "href" directly</a> 

This is the only <html:link> tag that isn't rewritten to URL encode the user's Session ID if the user has cookies turned off.

Create the Link as a Relative Link from the Current Page

This is the method to use if you're linking to another page within your application and you don't need to URL encode any request parameters into the request. Just create an <html:link> tag similar to the following:

 <html:link page="/HtmlBasic.do">   A relative link from this page </html:link> 

The HTML generated is

 <a href="/StrutsTaglibs/HtmlBasic.do">A relative link from this page</a> 
Hard-Code Request Parameters on the URL or URI

This section covers both <html:link> and <html:rewrite> .

This is the method to use if you need to create a URL or URI containing request parameters and the request parameters will never vary.

When you code the tag, simply add the request parameters to the end of the attribute specifying the page, similar to the following:

 <html:link page="/HtmlBasic.do?prop1=abc&amp;prop2=123">   Hard-code the url parameters </html:link> <%-- or --%> rewrite: <html:rewrite page="/HtmlBasic.do?prop1=abc&amp;prop2=123" /> 

The HTML generated is

[View full width]
 
[View full width]
<a href="/StrutsTaglibs/HtmlBasic.do?prop1=abc&amp;prop2=123"> Hard-code the url graphics/ccc.gif parameters</a> rewrite: /StrutsTaglibs/HtmlBasic.do?prop1=abc&amp;prop2=123
Encode a Single Request Variable on the URL or URI

This section covers both <html:link> and <html:rewrite> .

Use this approach if you have a single request parameter that you need to encode, and that value is (or can be) stored in a bean accessible to the page.

First, here's an example of how to save a value so that you can access it using this tag. The basic approach is to save it as an attribute on the page context. (This approach is used throughout Struts itself as a method to save and pass data around.)

 <%     /*      * Create a String object to store as a bean in      * the page context and embed in this link      */    String beanName = "Value to Pass on URL";    pageContext.setAttribute("pageAttribute1", beanName); %> 

Now the value is stored in the page context, ready to be passed to the tags like so:

 <%-- For this version of the <html:link> tag:                   --%> <%--   paramID = the name of the url parameter                    --%> <%--   paraName = the "attribute" for the bean holding the value  --%> <html:link page="/HtmlBasic.do"           paramId="urlParamName" paramName="pageAttribute1"> URL encode a parameter based on a bean value </html:link> <%-- Create the same rewrite string for the above link. --%> rewrite: <html:rewrite page="/HtmlBasic.do"               paramId="urlParamName" paramName="pageAttribute1" /> 

The HTML generated is

[View full width]
 
[View full width]
<a href="/StrutsTaglibs/HtmlBasic.do?urlParamName=Value+to+Pass+on+URL"> URL encode a graphics/ccc.gif parameter based on a bean value</a> rewrite: /StrutsTaglibs/HtmlBasic.do?urlParamName=Value+to+Pass+on+URL
Encode a Multiple Request Variables on the URL or URI

This section covers both <html:link> and <html:rewrite> .

Use this approach if you have multiple request parameters that you need to encode.

To pass multiple values to the tags, you must use a map. Several classes in the java.util package meet this criterion. Here's an example using java.util.HashMap :

 <%    /*     * Store values in a Map (HashMap in this case)     * and construct the URL based on the Map     */   java.util.HashMap myMap = new java.util.HashMap();   myMap.put("myString", new String("myStringValue") );   myMap.put("myArray", new String[] { "str1", "str2", "str3" });   pageContext.setAttribute("map", myMap); %> 

Note that one of the values stored in the HashMap is itself an array containing multiple values. Now everything is stored in the page context, ready to be passed to the tags like so:

 <%-- For this version of the <html:link> tag:             --%> <%-- map = a map with name/value pairs to pass on the url --%> <html:link page="/HtmlBasic.do" name="map">   URL encode a parameter based on values in a Map </html:link> <%-- Create the same rewrite string for the above link. --%> rewrite: <html:rewrite page="/HtmlBasic.do" name="map"/> 

The HTML generated is

[View full width]
 
[View full width]
<a href="/StrutsTaglibs/HtmlBasic.do?myString=myStringValue&amp;myArray=str1&amp; graphics/ccc.gif myArray=str2&amp;myArray=str3">URL encode a parameter based on values in a Map</a> rewrite: /StrutsTaglibs/HtmlBasic.do?myString=myStringValue&amp;myArray=str1&amp; graphics/ccc.gif myArray=str2&amp;myArray=str3

The <html:img> Tag

The <html:img> tag is used to embed images in HTML pages. Generally it's a simple, straightforward tag that simply links an image to the page. If needed, however, it can also pass request parameters along with its request. This might, for example, allow the images to be generated dynamically based on the passed parameters.

There are three examples of this tag's use in the sample application.

Generate a Basic <img> Tag Linking to an Image

This example simply generates a standard <img> tag:

 <html:img page="/struts-power.gif" /> 

The HTML generated is

 <img src="/StrutsTaglibs/struts-power.gif"> 
Generate an <img> Containing a Single Request Parameter

This example generates an <img> tag with a single request parameter. The parameter is created based on the stored bean from the corresponding <html:link> section earlier:

 <%-- Note "src" requires using full relative path --%> <html:img src="/StrutsTaglibs/struts-power.gif"           paramId="urlParamName" paramName="pageAttribute1" /> 

The HTML generated is

 <img src="/StrutsTaglibs/struts-power.gif?urlParamName=Value+to+Pass+on+URL"> 
Generate an <img> Containing a Multiple Request Parameters

This example generates an <img> tag with a multiple request parameters. The parameters are created based on the stored HashMap from the corresponding <html:link> section earlier:

 <html:img page="/struts-power.gif" name="map" /> 

The HTML generated is

[View full width]
 
[View full width]
<img src="/StrutsTaglibs/struts-power. graphics/ccc.gif gif?myString=myStringValue&myArray=str1&myArray=str2&myArray=str3">


Struts Kick Start
Struts Kick Start
ISBN: 0672324725
EAN: 2147483647
Year: 2002
Pages: 177

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net