Preface
Many times we face problems while accessing static resources through Servlet. Following blog post will explain one possible solution for this problem. It is applied in the web application that is only exposing Web Services to outside world.
Assume that the Web Application is already developed. However, currently the application does not have any static resources.
In the web.xml the Servlet serving Web Services is mapped with /* URL pattern.
For example,
<servlet> <servlet-name>WebServicesServlet</servlet-name> <servlet-class>FullyQualifiedClassName</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet Name</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
Requirement
This Web Application needs to be enhanced to
- Provide some functionality
- Develop a Web Interface for the above mentioned functionality
The Web Application contains static contents (e.g. JavaScript) files.
Problem
In Web Application, the JavaScript files are invoked through <script/> tags. These tags contain src attribute that has URL of JavaScript file.
As the Web Service servlet (WebServicesServlet) is mapped to /*, all the JavaScript URL will be answered by this servlet. The same servlet won’t be able to find JavaScript.
This will result in an error.
Solution
The above scenario has the following solutions.
Solution 1 - Application with Spring
Please go through the link below
http://static.springsource.org/spring-webflow/docs/2.3.x/reference/html/ch12s02.html
Solution 2 - Application with/ without Spring
Write a Servlet extending HttpServlet that will
- Find the path of Static Resource
- Read the Static Resource with FileInputStream
- Write the data to Response OutputStream
Implementation Steps
Web Application Structure (Tomcat Server)
Servlet Class: com.sample.servlet.TryServlet
Web.xml: Map this servlet
<servlet> <servlet-name>Static Resource Servlet</servlet-name> <servlet-class>com.sample.servlet.TryServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Static Resource Servlet</servlet-name> <url-pattern>/staticResources/*</url-pattern> </servlet-mapping>
URL of JavaScript File.
http://localhost:8080/.../staticResources/resources/js/sample.js
Servlet Code
init(ServletConfig)
- Get the Real path of Application on Server
servletConfig.getServletContext.getRealPath(“.”)
C:..Tomcatwebappssample.
doGet(HttpServletRequest, HttpServletResponse)
- Extract the path of JS under sample directory
- Concat path from #1 and #2. This is actual path of JS file
- Read the above file with FileInputStream
- Write the bytes from FileInputStream to response OutputStream
/resources/js/sample.js
C:..Tomcatwebappssample./resources/js/sample.js
Solution 3 - Filters
I found this solution on the below URL. However, I haven’t tried this solution.