<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Thoughts Electrique &#187; JSP</title>
	<atom:link href="http://www.sebastian.himberger.de/blog/tag/jsp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sebastian.himberger.de/blog</link>
	<description>Sebastian Himbergers blog about technology and software development</description>
	<lastBuildDate>Thu, 08 Jul 2010 17:05:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How to log in a user of a specified OpenCms OU</title>
		<link>http://www.sebastian.himberger.de/blog/2009/10/12/how-to-log-in-a-user-of-a-specified-opencms-ou/</link>
		<comments>http://www.sebastian.himberger.de/blog/2009/10/12/how-to-log-in-a-user-of-a-specified-opencms-ou/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 20:01:54 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[OpenCms]]></category>
		<category><![CDATA[OU]]></category>

		<guid isPermaLink="false">http://www.sebastian.himberger.de/blog/?p=538</guid>
		<description><![CDATA[I recently had to login a user of a specified OU (Organizational Unit) through a JSP. This is done by simply prepending the username with the path to the OU.
Example: I want to login the user &#8220;foo&#8221; of the OU &#8220;/germany/marketing&#8220;. Simple specify the String &#8220;/germany/marketing/foo&#8221; as a username and you&#8217;re all set.
]]></description>
			<content:encoded><![CDATA[<p>I recently had to login a user of a specified OU (Organizational Unit) through a JSP. This is done by simply prepending the username with the path to the OU.</p>
<p><strong>Example</strong>: I want to login the user &#8220;<em>foo</em>&#8221; of the OU &#8220;<em>/germany/marketing</em>&#8220;. Simple specify the String &#8220;<em>/germany/marketing/foo</em>&#8221; as a username and you&#8217;re all set.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sebastian.himberger.de/blog/2009/10/12/how-to-log-in-a-user-of-a-specified-opencms-ou/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSP to download OpenCms resources as a ZIP</title>
		<link>http://www.sebastian.himberger.de/blog/2009/06/25/jsp-to-download-opencms-resources-as-a-zip/</link>
		<comments>http://www.sebastian.himberger.de/blog/2009/06/25/jsp-to-download-opencms-resources-as-a-zip/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 18:09:38 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[OpenCms]]></category>
		<category><![CDATA[Sourcecode]]></category>
		<category><![CDATA[ZIP]]></category>

		<guid isPermaLink="false">http://www.sebastian.himberger.de/blog/?p=443</guid>
		<description><![CDATA[What often bugged me is that I can upload a set of files into OpenCms as a ZIP file but can not download a tree of files as such (without the use of the database export feature). I had hacked together this little JSP some time ago. It allows you to dynamically download a set [...]]]></description>
			<content:encoded><![CDATA[<p>What often bugged me is that I can upload a set of files into OpenCms as a ZIP file but can not download a tree of files as such (without the use of the database export feature). I had hacked together this little JSP some time ago. It allows you to dynamically download a set of OpenCms resources as a ZIP file.</p>
<p>The JSP has no interface since I mainly use it for development. Simply create a JSP somewhere in the OpenCms VFS and then open the file via the browser. E.g.:</p>
<p>&#8220;http://workplace.com/system/createzip?<strong>source</strong>=<em>/system/modules/foo</em>&amp;<strong>filename</strong>=<em>foo-module.zip</em>&#8221;</p>
<p>The <strong>source</strong> parameter specifies which directory to zip up and the <strong>filename</strong> parameter which filename to use for the generated file. You can only zip up resources with a total size of 10 megabytes. This is mainly to prevent OutOfMemory errors to happen. You can easily increase the size by altering the variable <strong>maxSourceSize</strong> to any value you need.</p>
<p>If you find any bugs or want to give feedback simply leave a comment or send me an email.</p>
<p><span id="more-443"></span></p>
<pre class="file">&lt;%@page import="org.opencms.util.*,
                org.opencms.jsp.*,
                org.opencms.file.*,
                java.util.*,
                java.io.*,
                java.util.zip.*
" %&gt;&lt;%

// Maximum filesize to prevent OutOfMemory errors
long maxSourceSize = 1024*1024*10; // 10 Megabytes

// The filename to use as output
String filename = request.getParameter("filename");

// The directory to zip
String source = request.getParameter("source");

if (CmsStringUtil.isEmpty(filename) || CmsStringUtil.isEmpty(source )) {
  // Ensure that all parameters are given
  throw new IllegalArgumentException("Please specify the 'source' and the 'filename' parameter");
}

if (!source.endsWith("/")) { source = source + "/"; }

CmsJspActionElement cmsa = new CmsJspActionElement(pageContext,request,response);
CmsObject cmso = cmsa.getCmsObject();
List zipResources = new ArrayList();

// Collect all the resources
CmsResource sourceResource = cmso.readResource(source);
if (!sourceResource.isFolder()) {
  throw new IllegalArgumentException("Please specify a folder to zip");
}
List cmsResources = cmso.readResources(source,CmsResourceFilter.DEFAULT);
for (Iterator i = cmsResources.iterator(); i.hasNext();) {
  zipResources.add(i.next());
}

// Create the zip file
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zipfile = new ZipOutputStream(bos);

long currentSize = 0;
for (Iterator i = zipResources.iterator(); i.hasNext(); ) {
  CmsResource res = (CmsResource) i.next();

  currentSize += res.getLength();
  if (currentSize &gt; maxSourceSize) {
    // Ensure that we don't zip up too much
    throw new RuntimeException("Source size is bigger than: " + (maxSourceSize/1024) + " kilobytes");
  }

  String sourcePath = cmso.getRequestContext().getSitePath(res);
  String targetPath = sourcePath;
  if (targetPath.startsWith(source)) {
    targetPath = targetPath.substring(source.length());
  }

  //out.println("Zipping " + sourcePath + " as " + targetPath + "&lt;br/&gt;");
  if (res.isFile()) {
  ZipEntry zipentry = new ZipEntry(targetPath);
  zipfile.putNextEntry(zipentry);
      CmsFile file = cmso.readFile(res);
      zipfile.write(file.getContents(),0,file.getLength());
  }
}

zipfile.close();
byte[] content = bos.toByteArray();

response.setContentType("application/octet-stream");
response.setContentLength((int)content.length);
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"" );

response.getOutputStream().write(content,0,content.length);
response.getOutputStream().flush();

%&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sebastian.himberger.de/blog/2009/06/25/jsp-to-download-opencms-resources-as-a-zip/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manipulating OpenCms XMLContent programatically (some examples)</title>
		<link>http://www.sebastian.himberger.de/blog/2008/12/12/manipulating-opencms-xmlcontent-programatically-some-examples/</link>
		<comments>http://www.sebastian.himberger.de/blog/2008/12/12/manipulating-opencms-xmlcontent-programatically-some-examples/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 15:12:15 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Example]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[OpenCms]]></category>
		<category><![CDATA[Sourcecode]]></category>

		<guid isPermaLink="false">http://www.sebastian.himberger.de/blog/?p=253</guid>
		<description><![CDATA[Because someone asked on the mailing list and I keep forgetting the respective API calls to manipulate an OpenCms XMLContent programatically.
This is just a raw code dump not a step by step tutorial.
You can also download a ZIP file for importing it into OpenCms. But you have to adjust the paths manually.


Example JSP calls
&#60;%@ page [...]]]></description>
			<content:encoded><![CDATA[<p>Because someone asked on the mailing list and I keep forgetting the respective API calls to manipulate an OpenCms XMLContent programatically.</p>
<p><strong>This is just a raw code dump not a step by step tutorial</strong>.</p>
<p><a href="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/example-xmlcontent-20081212.zip">You can also download a ZIP file</a> for importing it into OpenCms. But you have to adjust the paths manually.<a href="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/example-xmlcontent-20081212.zip"><br />
</a></p>
<p><span id="more-253"></span></p>
<h3>Example JSP calls</h3>
<pre class="file">&lt;%@ page import="org.opencms.file.*,
                 org.opencms.jsp.*,
                 org.opencms.xml.*,
                 org.opencms.xml.content.*,
                 org.opencms.xml.types.*,
                 org.opencms.util.*,
                 java.util.*" %&gt;&lt;%

// The resource to read
String resource = "/system/modules/de.himberger.sebastian.site/schemas/publication/manipulate.html";

// The locale to use
Locale locale = new Locale("en");

// The names of the elements
String versionElement = "Version";
String fileElement = "File";

CmsJspActionElement cmsa = new CmsJspActionElement(pageContext,request,response);
CmsObject cmso = cmsa.getCmsObject();

// read the resource
CmsResource xmlContentResource = cmso.readResource(resource);
CmsFile xmlContentFile = CmsFile.upgrade(xmlContentResource,cmso);

// Output current xml
out.println("&lt;h1&gt;Before&lt;/h1&gt;");
out.println("&lt;pre&gt;" + CmsStringUtil.escapeHtml((new String(xmlContentFile.getContents()))) + "&lt;/pre&gt;");

// build up the xml content instance
CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(cmso,xmlContentFile);

// This is a new version (in this case it is a nested schema
I_CmsXmlContentValue addedVersionValue = xmlContent.addValue(cmso,versionElement ,locale,0);

// Add a new element to the created version (nested schema)
I_CmsXmlContentValue addedFileValueRaw = xmlContent.addValue(
  cmso,addedVersionValue.getPath() + "/" + fileElement,locale,0);
CmsXmlVfsFileValue addedFileValue = (CmsXmlVfsFileValue ) addedFileValueRaw;
addedFileValue.setStringValue(cmso,resource);

// manipulate an element
I_CmsXmlContentValue theSameValueWeAdded = xmlContent.getValue(
  addedVersionValue.getPath() + "/" + fileElement,locale);
// ... do the same as above

// add and remove a value
I_CmsXmlContentValue secondAddedVersionValue = xmlContent.addValue(cmso,
  versionElement,locale,addedVersionValue.getIndex()+1);

out.println("&lt;h1&gt;After adding&lt;/h1&gt;");
out.println("&lt;pre&gt;" + CmsStringUtil.escapeHtml((new String(xmlContent.marshal()))) + "&lt;/pre&gt;");

xmlContent.removeValue(secondAddedVersionValue.getPath(),locale,0);

out.println("&lt;h1&gt;After removing&lt;/h1&gt;");
out.println("&lt;pre&gt;" + CmsStringUtil.escapeHtml((new String(xmlContent.marshal()))) + "&lt;/pre&gt;");

// In the real world you would now do
// xmlContentFile.setContents(xmlContent.marshal());
// cmso.writeResource(xmlContentFile);
%&gt;</pre>
<h3>Version schema</h3>
<pre class="file">&lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"&gt;

       &lt;xsd:include schemaLocation="opencms://opencms-xmlcontent.xsd"/&gt;
       &lt;xsd:element name="XmlContentPublicationVersions"
                    type="OpenCmsXmlContentPublicationVersions"/&gt;

       &lt;xsd:complexType name="OpenCmsXmlContentPublicationVersions"&gt;
               &lt;xsd:sequence&gt;
                       &lt;xsd:element name="XmlContentPublicationVersion"
                                    type="OpenCmsXmlContentPublicationVersion"
                                    minOccurs="0" maxOccurs="unbounded"/&gt;
               &lt;/xsd:sequence&gt;
       &lt;/xsd:complexType&gt;

       &lt;xsd:complexType name="OpenCmsXmlContentPublicationVersion"&gt;
              &lt;xsd:sequence&gt;
                      &lt;xsd:element name="Title" type="OpenCmsString" /&gt;
		      &lt;xsd:element name="PublicationDate" type="OpenCmsDateTime" /&gt;
                      &lt;xsd:element name="Description" type="OpenCmsString" /&gt;
                      &lt;xsd:element name="File" type="OpenCmsVfsFile" minOccurs="0"
                                   maxOccurs="10" /&gt;
              &lt;/xsd:sequence&gt;
              &lt;xsd:attribute name="language" type="OpenCmsLocale" use="optional"/&gt;
       &lt;/xsd:complexType&gt;

&lt;/xsd:schema&gt;</pre>
<h3>Publication schema</h3>
<pre class="file">&lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"&gt;

       &lt;xsd:include schemaLocation="opencms://opencms-xmlcontent.xsd"/&gt;
       &lt;xsd:include
            schemaLocation="opencms://system/modules/de.himberger.sebastian.site/schemas/publication/publication-version.xsd"/&gt;

       &lt;xsd:element name="XmlContentPublications" type="OpenCmsXmlContentPublications"/&gt;

       &lt;xsd:complexType name="OpenCmsXmlContentPublications"&gt;
               &lt;xsd:sequence&gt;
                       &lt;xsd:element name="XmlContentPublication"
                                    type="OpenCmsXmlContentPublication"
                                    minOccurs="0" maxOccurs="unbounded"/&gt;
               &lt;/xsd:sequence&gt;
       &lt;/xsd:complexType&gt;

       &lt;xsd:complexType name="OpenCmsXmlContentPublication"&gt;
              &lt;xsd:sequence&gt;
                      &lt;xsd:element name="Title" type="OpenCmsString" /&gt;
                      &lt;xsd:element name="Subtitle" type="OpenCmsString" /&gt;
                      &lt;xsd:element name="Description" type="OpenCmsHtml" /&gt;
                      &lt;xsd:element name="Version"
                                   type="OpenCmsXmlContentPublicationVersion"
                                   minOccurs="0" maxOccurs="unbounded" /&gt;
              &lt;/xsd:sequence&gt;
              &lt;xsd:attribute name="language" type="OpenCmsLocale" use="required"/&gt;
       &lt;/xsd:complexType&gt;

&lt;/xsd:schema&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sebastian.himberger.de/blog/2008/12/12/manipulating-opencms-xmlcontent-programatically-some-examples/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Use the power of JSP tag files in OpenCms</title>
		<link>http://www.sebastian.himberger.de/blog/2008/12/12/use-the-power-of-jsp-tag-files-in-opencms/</link>
		<comments>http://www.sebastian.himberger.de/blog/2008/12/12/use-the-power-of-jsp-tag-files-in-opencms/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 09:22:38 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[OpenCms]]></category>
		<category><![CDATA[Sourcecode]]></category>
		<category><![CDATA[Taglibs]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sebastian.himberger.de/blog/?p=220</guid>
		<description><![CDATA[Since version 7 OpenCms is a Servlet 2.4 and JSP 2.0 conforming application. In addition to the improved expression language (EL) JSP 2.0 also brings in the possibility of developing custom tags(actions) using JSP rather than writing Java code. This allows for some pretty neat things and enables you to go one step further towards [...]]]></description>
			<content:encoded><![CDATA[<p>Since version 7 OpenCms is a <em>Servlet 2.4</em> and <em>JSP 2.0</em> conforming application. In addition to the improved expression language (<em>EL</em>) JSP 2.0 also brings in the possibility of developing custom tags(actions) using JSP rather than writing Java code. This allows for some pretty neat things and enables you to go one step further towards cleaner view code. I&#8217;ve used this in one of my last projects extensively to refactor common code like pagers and link generation. For example:</p>
<pre class="file">&lt;cms:include file="/system/modules/com.example.ocms.commons/elements/pager"&gt;
  &lt;cms:param name="currentPage"&gt;
    &lt;c:out value="${model.currentPage}"/&gt;
  &lt;/cms:param&gt;
  &lt;cms:param name="pageCount"&gt;
    &lt;c:out value="${model.pageCount}"/&gt;
  &lt;/cms:param&gt;
&lt;/cms:include&gt;</pre>
<p>Became:</p>
<pre class="file">&lt;wt:pager model="${model}"/&gt;</pre>
<p>Not does it only look cleaner and is much more focused, it also decouples your view more from the underlying CMS solution. Of course you could also develop a custom tag library using Java (which I have done a few times) but using a JSP the advantage that code can be changed on the fly and even from a web designer. You can always refactor your JSP taglib into a Java one if you need to do it. There are some limitations of JSP tag files (like you can&#8217;t use scriptlets in the body) but they are easy to get around.</p>
<p><strong>But as always:</strong> This is no silver bullet. There are problems with tag files which may not be obvious at the first glance.</p>
<p><span id="more-220"></span></p>
<h3>How to create a tag</h3>
<p>Creating a tag is easy. I will show you the necessary steps while developing a tag which allows the user to loop over the contents of an OpenCms <a href="http://www.opencms-wiki.org/Virtual_File_System">VFS</a> directory.</p>
<h4>Preparing your module</h4>
<p>As normal Java libraries too, JSP tags need to be exported into the filesystem to be read by the <a href="http://en.wikipedia.org/wiki/Java_Servlet#Servlet_containers">Servlet-Container</a>. Normally the tag files reside under a directory like <em>${yourwebapp}/WEB-INF/tags/mylibrary</em>. So what we will do is adding a new export point to the module containing our tag files.</p>
<p>First we create a new directory called <em>tags </em>inside the module we want to contain our tags (normally I create a module for each site). The resulting structure will look something like this</p>
<div id="attachment_227" class="wp-caption aligncenter" style="width: 510px"><a href="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/create-tags-folder.png"><img class="size-full wp-image-227" title="The tags folder inside the module directory" src="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/create-tags-folder.png" alt="The tags folder inside the module directory" width="500" height="154" /></a><p class="wp-caption-text">The tags folder inside the module directory</p></div>
<p>Then we open the module administration and add an export point to our module (<em>Administration -&gt;  	<span class="link" onclick="openPage('/system/workplace/views/admin/admin-main.jsp?path=/modules');" onmouseover="sMH('navtool7');" onmouseout="hMH('navtool7');"><span style="white-space: nowrap;">Module Management</span></span> -&gt; Edit Your module -&gt; Module exportpoints -&gt; New exportpoint</em>).</p>
<div id="attachment_228" class="wp-caption aligncenter" style="width: 510px"><a href="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/add-exportpoint.png"><img class="size-full wp-image-228" title="Adding the tags exportpoint" src="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/add-exportpoint.png" alt="Adding the tags exportpoint" width="500" height="138" /></a><p class="wp-caption-text">Adding the tags exportpoint</p></div>
<p>After pressing <em>OK</em> we are well prepared to add custom tags to our OpenCms module.</p>
<h4>Creating the tag file</h4>
<p>We now create a directory for our taglib. This will be located inside our newly created <em>tags </em>folder. Because we want to create a tag which interacts with the OpenCms VFS we will simply call the folder <em>vfs</em>. Inside this directory we create a new JSP resource called <em>directoryLoop.tag</em>. The result should look something like this:</p>
<div id="attachment_230" class="wp-caption aligncenter" style="width: 510px"><a href="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/the-tag-file.png"><img class="size-full wp-image-230" title="The created tag file in the VFS" src="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/the-tag-file.png" alt="The created tag file in the VFS" width="500" height="57" /></a><p class="wp-caption-text">The created tag file in the VFS</p></div>
<p>Now it&#8217;s time to write some code <img src='http://www.sebastian.himberger.de/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<h4>Writing the tag file</h4>
<p>I don&#8217;t want to go into the details of developing tag files in general. This topic has been covered by dozens of books and online tutorials. I have collected some links in this blog post which explain the development of tag files in detail. Have a look at the section <em>Further reading</em> if you want to find out.</p>
<p>I will assume you&#8217;ve already developed JSP files inside OpenCms so I won&#8217;t explain the steps in detail. If you have questions regarding the sourcecode simply post a comment.</p>
<p>Here&#8217;s the commented sourcecode for our tag file.</p>
<pre class="file">&lt;%@ tag body-content="scriptless" %&gt;
&lt;%@ tag import="org.opencms.jsp.*,
                org.opencms.file.*,
                java.util.*" %&gt;
&lt;%@ attribute name="folder" required="true" %&gt;
&lt;%@ variable name-given="resource" scope="NESTED" %&gt;
&lt;%@ variable name-given="status" scope="NESTED" %&gt;
&lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt;&lt;%

// First we get the pageContext variable.
// Tag files only have an explicit JspContext but in this case
// it is a PageContext which is a subclass of JspContext.
PageContext pageContext = (PageContext)jspContext;

// Instantiate the usual CmsObject to access OpenCms data
CmsJspActionElement cmsa = new CmsJspActionElement(pageContext ,request,response);
CmsObject cmso = cmsa.getCmsObject();

// Read the resources, note that we can access the tag
// parameters using the pageContext.
String folder = (String) pageContext.getAttribute("folder");
folder = cmso.getRequestContext().removeSiteRoot(folder);
List resources = cmso.readResources(folder,CmsResourceFilter.DEFAULT,false);

// We store the list of resources in the pageContext for usage with JSTL
pageContext.setAttribute("resources",resources);

%&gt;

&lt;c:forEach var="resource" items="${resources}" varStatus="status"&gt;
  &lt;jsp:doBody/&gt;
&lt;/c:forEach&gt;</pre>
<p>As you can see the tag file looks like a usual JSP file with only a few differences.</p>
<p>The tag exports two variables: The <em>current resource</em> and the <em>iteration status</em>. These can be accessed from the invoking JSP. We will make use of this in the next example.</p>
<p><strong>To use the tag you have to publish the file</strong> so it gets written to the file system. After you&#8217;re finished writing/modifying the tag: Don&#8217;t forget to publish it!</p>
<p><strong>You can&#8217;t preview tags</strong>, even though they are JSP files. You also won&#8217;t get compiler warnings. You always need a JSP file to test your tag files.</p>
<h4>Using the created tag</h4>
<p>We will use the created tag to implement a simple file browser. The file browser displays the contents of a folder and allows the user to navigate into subfolders recursively. Please note that <strong>this is definately no production ready code</strong>.</p>
<pre class="file"><strong>&lt;%@ taglib prefix="vfs" tagdir="/WEB-INF/tags/vfs" %&gt;</strong>
&lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt;

&lt;%-- Determine the current folder, set to "/" if no parameter given --%&gt;
&lt;c:set var="folder" value="${param.folder}"/&gt;
&lt;c:if test="${folder eq '' or folder == null}"&gt;
  &lt;c:set var="folder" value="/"/&gt;
&lt;/c:if&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;style type="text/css"&gt;

   .row-1 {
     background-color: #ECECEC;
   }

  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Resources of folder "${folder}"&lt;/h1&gt;
&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;&lt;/th&gt;
    &lt;th&gt;Name&lt;/th&gt;
    &lt;th&gt;Size&lt;/th&gt;
    &lt;th&gt;Date created&lt;/th&gt;
  &lt;/tr&gt;
<strong>  &lt;vfs:directoryLoop folder="${folder}"&gt;</strong>
  &lt;%-- We use the status for alternating row classes, useful for css --%&gt;
  &lt;tr class="row-${status.count % 2}"&gt;
    &lt;td&gt;
      &lt;%-- Display D for directory or F for file --%&gt;
      &lt;c:choose&gt;
        &lt;c:when test="${resource.folder}" &gt;D&lt;/c:when&gt;
        &lt;c:otherwise&gt;F&lt;/c:otherwise&gt;
      &lt;/c:choose&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;%-- If the current resource is a folder, display a link --%&gt;
      &lt;c:choose&gt;
        &lt;c:when test="${resource.folder}" &gt;
          &lt;a href="?folder=${resource.rootPath}"&gt;${resource.name}&lt;/a&gt;
        &lt;/c:when&gt;
        &lt;c:otherwise&gt;${resource.name}&lt;/c:otherwise&gt;
      &lt;/c:choose&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;%-- If the current resource is a file, display size --%&gt;
      &lt;c:if test="${!resource.folder}"&gt;${resource.length}&lt;/c:if&gt;
    &lt;/td&gt;
    &lt;td&gt;${resource.dateCreated}&lt;/td&gt;
  &lt;tr&gt;
<strong>  &lt;/vfs:directoryLoop&gt;</strong>
&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>As you can see the tags are included with the directive.</p>
<pre class="file"><strong>&lt;%@ taglib prefix="vfs" tagdir="/WEB-INF/tags/vfs" %&gt;
</strong></pre>
<p>The usage of the tags is similar to normal tags with the exception that you can&#8217;t use scriptlets in the tag bodies. If the example is working you should see something like the following.</p>
<div id="attachment_241" class="wp-caption aligncenter" style="width: 510px"><a href="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/ouput.png"><img class="size-full wp-image-241" title="The output of the created JSP" src="http://www.sebastian.himberger.de/blog/wp-content/uploads/2008/12/ouput.png" alt="The output of the created tag" width="500" height="178" /></a><p class="wp-caption-text">The output of the created JSP</p></div>
<p>If you have trouble reading the above code. Here is a more condensed version of a file using the tag:</p>
<pre><strong>&lt;%@ taglib prefix="vfs" tagdir="/WEB-INF/tags/vfs" %&gt;</strong>
&lt;ul&gt;
<strong>&lt;vfs:directoryLoop folder="/system/modules"&gt;</strong>
  &lt;li&gt;${resource.name}&lt;/li&gt;
<strong>&lt;/vfs:directoryLoop&gt;</strong>
&lt;/ul&gt;</pre>
<h3>Things to keep in mind</h3>
<p>JSP tag files and OpenCms really are a nice fit, but before you start working on converting all your custom includes to tag files keep in mind some of the disadvantages of tag files in respect to using <em>&lt;cms:include&gt;</em>.</p>
<ul>
<li><strong>Tag files are not seperated by online/offline</strong>. Since the tag files only get exported during publishing there is no way of developing the tags in the offline project. You always have to publish the tag file to see your changes (It&#8217;s like a normal, Java based, tag library). This means if you have an error in your code the live system will be affected by it. In my opinion this problem is not as big as it sounds. Tags are normally developed in a staged environment or on a developer machine and then deployed on the live server. Additionally they are no replacement for templates and therefore shouldn&#8217;t be changed often.</li>
<li><strong>Tag files are not cached</strong>. The output of a <em>&lt;cms:include&gt;</em> may be cached by the OpenCms FlexCache. This can speed up the rendering enormously, tag files are always processed. In my opinion this no big problem. Tag files will mostly always be used in JSP templates which in turn will be cached by the FlexCache. I would suggtest that tag files are used as the building blocks for JSP templates and therefore are one a finer granular level. The chunks you want to cache are normally much more coarse grained.</li>
</ul>
<h3>Finishing thoughts</h3>
<p>In my opinion JSP tag files are a great thing. They can help you clean up messy JSP templates and nicely decouple your JSPs from OpenCms (although I used a pretty OpenCms heavy example in this post). I hope this post was useful and helped you adding another tool to your toolbox. If you have further questions or need help regarding a specific project, please leave a comment or <a href="/contact">contact me directly</a>.</p>
<h3>Further Reading</h3>
<p>These tutorials can help you developing your own tag files or looking up classes used in this tutorial.</p>
<ul>
<li><a title="Encapsulating Reusable Content Using Tag Files" href="http://java.sun.com/javaee/5/docs/tutorial/doc/bnama.html" target="_blank">The JEE 5 tutorial on creating tag files</a></li>
<li><a title="Creating JSP 2.0 Tag Files" href="http://www.oracle.com/technology/pub/articles/cioroianu_tagfiles.html" target="_blank">An online tutorial on JSP tag files by Oracle</a></li>
<li><a title="Easy Custom Tags with Tag Files" href="http://today.java.net/pub/a/today/2003/11/14/tagfiles.html" target="_blank">A java.net article on tag files, short and good</a></li>
<li><a title="The OpenCms JavaDoc" href="http://files.opencms.org/javadoc/core/" target="_blank">The OpenCms JavaDoc, always handy</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.sebastian.himberger.de/blog/2008/12/12/use-the-power-of-jsp-tag-files-in-opencms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Display RSS Feeds in JSPs with RSS4JSP</title>
		<link>http://www.sebastian.himberger.de/blog/2008/12/11/display-rss-feeds-in-jsps-with-rss4jsp/</link>
		<comments>http://www.sebastian.himberger.de/blog/2008/12/11/display-rss-feeds-in-jsps-with-rss4jsp/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 11:40:47 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Rome]]></category>
		<category><![CDATA[RSS]]></category>
		<category><![CDATA[Taglib]]></category>

		<guid isPermaLink="false">http://www.sebastian.himberger.de/blog/?p=217</guid>
		<description><![CDATA[I recently discovered the freshly released RSS4JSP tag library. Its a wrapper around the mature and widely used Rome RSS library which was developed by Sun and then open sourced. The library allows you to simply display (news) feeds inside your JSP pages.
While it&#8217;s certainly a young project, I found it very useful and easy [...]]]></description>
			<content:encoded><![CDATA[<p>I recently discovered the freshly released <a href="http://sourceforge.net/projects/rss4jsp/">RSS4JSP </a>tag library. Its a wrapper around the mature and widely used <a href="https://rome.dev.java.net/">Rome RSS library</a> which was developed by Sun and then open sourced. The library allows you to simply display (news) feeds inside your JSP pages.</p>
<p>While it&#8217;s certainly a young project, I found it very useful and easy to use. I gave it a try to create the <em>Latest blog posts</em> box on my, OpenCms based, <a href="http://www.sebastian.himberger.de/">homepage</a>. The box was created during 5 minutes which I think is impressive (given that you have to type the HTML too).</p>
<p>Unfortunately the project does not allow the syndication of multiple feeds into one feed (This is a nice feature of Rome which I used in a recent project) but maybe it will be added in the future (or I will add it myself).</p>
<p><a title="RSS4JSP at Sourceforge" href="https://sourceforge.net/projects/rss4jsp/" target="_blank">Check it out at sourceforge</a> or <a title="rss4jsp: A Tag Library for Project Rome" href="http://philhaigh.blogspot.com/2008/11/rss4jsp-tag-library-for-project-rome.html" target="_blank">visit the authors blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sebastian.himberger.de/blog/2008/12/11/display-rss-feeds-in-jsps-with-rss4jsp/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Better SEO for external links in OpenCms Navigation</title>
		<link>http://www.sebastian.himberger.de/blog/2008/11/26/better-seo-for-external-links-in-opencms-navigation/</link>
		<comments>http://www.sebastian.himberger.de/blog/2008/11/26/better-seo-for-external-links-in-opencms-navigation/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 14:10:25 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[OpenCms]]></category>
		<category><![CDATA[SEO]]></category>
		<category><![CDATA[Sourcecode]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sebastian.himberger.de/blog/?p=202</guid>
		<description><![CDATA[The Problem
If you put an external link into the OpenCms navigation the resulting link will target the external link file which then in turns redirects the surfer to the external page. This is bad if you really want to optimize your navigation for search engines, because search engines won&#8217;t see the real link inside the [...]]]></description>
			<content:encoded><![CDATA[<h3>The Problem</h3>
<p>If you put an external link into the OpenCms navigation the resulting link will target the external link file which then in turns redirects the surfer to the external page. This is bad if you really want to optimize your navigation for search engines, because search engines won&#8217;t see the real link inside the navigation.</p>
<h3>The solution</h3>
<p>You can use the following JSP snippet to get the real URL from a <a href="http://files.opencms.org/javadoc/core/org/opencms/jsp/CmsJspNavElement.html" target="_blank">CmsJspNavElement</a>.</p>
<pre>// We assume that the variable "link" holds an <a href="http://files.opencms.org/javadoc/core/org/opencms/jsp/CmsJspNavElement.html" target="_blank">CmsJspNavElement</a> and
// "cmsa" holds an <a href="http://files.opencms.org/javadoc/core/org/opencms/jsp/CmsJspActionElement.html" target="_blank">CmsJspActionElement</a>.

// Prevent external links from beeing a redirect
// therefore extract the real URL out of the file
String fileUri = link.getResourceName();
CmsResource navResource = cmsa.getCmsObject().readResource(fileUri);
if (navResource.getTypeId() == CmsResourceTypePointer.getStaticTypeId()) {
    CmsFile navFile = CmsFile.upgrade(navResource,cmsa.getCmsObject());
    String externalLink = new String(navFile.getContents());
    externalLink = externalLink.trim();
}</pre>
<h3>Further reading</h3>
<ul>
<li><a href="http://files.opencms.org/javadoc/core/index.html">The OpenCms JavaDoc</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.sebastian.himberger.de/blog/2008/11/26/better-seo-for-external-links-in-opencms-navigation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
