Philip's Files
Wednesday, May 30, 2012
Creating a filesystem URL in a JSP file.
I've been playing with producing SVG and PDF files by using JSP files to render the markup and then using a converter (e.g. Batik or Flying Saucer) to produce the final output using a transcoding servlet.
One problem with this approach is that the converter doesn't usually understand the URLs contained in the JSP markup.
I'm using the following recipe to convert relative paths to produce file URLs:
<%=(new java.io.File(application.getRealPath("/")+"relative_path_to/file.PNG")).toURL()%>Explanation:
- <%= is the Sciptlet Expression Tag. The following text will be a java snippet that will be run and it's output will be included in the generated page output.
- application is an Implicit object automatically defined for a JSP. It exposes the ServletContext object.
- getRealPath is called on the ServletContext object and returns the real filesystem path associated with a virtual path. This is called on "/" to get the base of the expanded WAR file.
- new java.io.File() is called on the string resulting from the relative path appended to the real path to create (but not open!) a File object.
- .toURL() is called on the file object to produce a File URL that most generators should understand.
This works for me on JBoss 4.5 - it might not work in all contexts.
The WAR is assumed to be exploded/expanded and not contained in a single Zip file.
Example use:
E.g. in a stylesheet:
See A related StackOverflow question
.head-item {
padding: 0%;
background-color: red;
text-align: center;
font-style: bold;
font-size: 150%;
background-image: url(<%=(new java.io.File(application.getRealPath("/")+"horisontal_red_to_pink_fade.PNG")).toURL()%>);
}
