Best practice of referencing resouces(css,img,js) in Portlet JSP

Any Portlet or j2ee Web application always include resources like css, images, js files.
In a web application, you can directly refer these resources using relative urls, but for Portlet Application it is NOT a good practice to use relative urls for including these types of resources.

For example:-
<link rel="stylesheet" href="../css/styles.css" type="text/css" />
Works well in a WebApplication.
BUT, in a portlet application, this will be interpreted relative to the portal 
url by the browser and thus will not point to the resource you 
intend to embed in your markup. 
So basically, if the css and jsp are both present in a sub folder of the root
folder of your portlet application, It would be resolved by the browser 
something like this
http://myserver/portalservlet-webapp-context+path/css/styles.css 
Which is not the case and you would like browser to request like this 
What you would like the browser to request is 
http://myserver/myportlet-webapp-context/css/styles.css
 
So, in portlet you should be using absolute path including
the context path of your portlet app 
<link rel="stylesheet" 
href="/<%=request.getContextPath()%>/css/styles.css"
type="text/css"/>
 
 
 

5 comments:

Naga said...

To further enhance this, it is Best Practice to store the css/js/image files on web server and not inside the Portlet, The web server path should be added as prefix while accessing the corresponding files. so instead of <link rel="stylesheet" href="../css/styles.css" type="text/css" /> we can use something like below
<c:set var="cssFolder" value="${webServerPath}/css" />

<link rel="stylesheet" href="${cssFolder}/styles.css" type="text/css" />

above syntax is using jstl and assumes that the web server path is retrieved and stored in a request/session variable with name webServerPath.

Neeraj Sidhaye said...

Hi Naga,
thanks for your comment.To add here, keeping css,img,js on WebServer should be done when these are part of Portal Theme and not for portlet app because different portlet apps might have different css,js and img and should be placed within portlet WAR.

php development said...

very nice post

designing said...

nice post.i like your post.

Java Training in Bangalore said...

Well explanation.Thanks for sharing...!