How to Access Files in Portlets
When developing a portlet, there will be many times in which
you need to read or write information to a file. However, you cannot use the File or FileReader/Writer classes in your portlet code because
these constructors require the exact location of the file you are opening,
which you do not know at the time of developing your portlet. This tip
describes how files can be accessed in your portlet code.
eg
images
|-img1.gif
|-img2.gif
html
|-static.html
PORTLET-INF
|-portlet.xml
|-classes
|- class files….
|-resources
|-news
|-html
|- news.html
|-ja
|-news.html
|-zh
|-news.html
|-wml
……
|-xsl
|-news.xsl
Note:
images and html folder names are arbitary, PORTLET-INF is required.
images and html folders to the <wps_root>\app\web\portlets\yourparfilename
directory. It will expand the PORTLET-INF
folder to the <wps_root>\app\web\WEB-INF\portletapps\yourparfilename
directory.images/html
folder and the PORTLET-INF
folder is that the files in images/html
folders can be accessed directly by the client browser, but not those in PORTLET-INF. On the other hand,
files in the PORTLET-INF
folder can be accessed by your portlet’s java code, but not those in images/html folder. Note also the
folder structure for multimarkup and multilanguage support.PORTLET-INF
folder, and those files that you want the client browsers to access via
the JSPs in the images/html
folders.PORTLET-INF
folder) from your java code, use the getResourceAsStream()
method of the PortletContext
class:eg
InputStream stylesheetIOS =
getPortletConfig().getContext().getResourceAsStream(“/PORTLET-INF/resources/xsl/news.xsl”);
for multi-language support:
eg
InputStream newsIOS =
getPortletConfig().getContext().getResourceAsStream(“/PORTLET-INF/resources/news/news.html”,htmlClient,chineseLocale);
See the
javadocs of the PortletContext
class for details of these two methods.
Note that you need to specify the “/PORTLET-INF” root in
the resource path.
What happens if you don’t?
If you specify something like
this:
getPortletConfig().getContext().getResourceAsStream(“/resources/xsl/news.xsl”);
The portal engine will look
for the news.xsl file in the following directory:
<wps_root>\web\app\WEB-INF\portlets\resources\xsl\news.xsl for your file.
The problem with this is that
there is no way for you to create your par file such that WPS will expand your xsl
file to this directory. You will need the WPS administrator to create the
directory manually after he installs your par file.
images/html
folder, you need to call the encodeURI() method of the implicit portlet
response object to create the URL.eg
<TD><IMG src="<%=response.encodeURI("images/img1.gif")%>"></TD>
or
<TD><IMG src="<%=response.encodeURI("/images/img1.gif")%>"></TD
Both the paths will map to <wps_root>\app\web\portlets\yourparfilename\images\img1.gif.