Struts Tip #9 - Use rewrite to reference HTML assets

Ted Husted

 

 

The Struts <html:rewrite> tag can convert a context-relative URI into a base URI that can be used to access style sheets, JavaScripts, images and other HTML assets. For example,

    <LINK rel="stylesheet" type="text/css" 
        HREF="<html:rewrite page='/assets/styles/base.css'/>">

If you wanted to hedge your bets about where the style sheets will be located, an ActionForward may also be used.

    <LINK rel="stylesheet" type="text/css" 
        HREF="<html:rewrite forward='baseStyle'/>">

Likewise, references to JavaScripts, as well as URIs to be processed by JavaScripts, can be rendered this way.

    <SCRIPT language='javascript'> 
       SRC='<html:rewrite page="/assets/scripts/remote.js"/>'>
    </SCRIPT> 
    <SCRIPT> 
    <!-- 
    function doScript(aScript) { 
        aBase = '<html:rewrite forward="scriptPreview"/>'; 
        HC_doOpenRemote(aBase + '?script=' + aScript); } 
    // -- 
    </SCRIPT>

In the latter example, we retrieve the base URI for the JavaScript function from an ActionForward and then append the script number based to the function. This type of function would usually be called from a hyperlink like this:

    <A HREF='javascript:doScript(10011)'>10011</A>

that was generated using JSP code like this:

    <A HREF='javascript:doScript(<bean:write name="row" property="script"/>)'> 
        <bean:write name="row" property="script"/> </A>

Since we are calling a JavaScript function, we did not bother with a <html:link> tag to provide URL encoding. The hyperlink will be handled client-side so maintaining the session is not an issue. The URI generated by the <rewrite> tag, and subsequently used by the Javascript, will be URL encoded, so that the session will be maintained if cookies are not present.

HTH - Ted.

-----

Struts Tips  are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.

About Ted. Ted Husted is an active Struts Committer and co-author of Java Web Development with Struts and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.

Copyright Ted Husted 2002. All rights reserved.

---

MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers

 

 

 

 

 

 

 

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact