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>
This Web Application needs to be enhanced to
The Web Application contains static contents (e.g. JavaScript) files.
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.
The above scenario has the following solutions.
Please go through the link below
http://static.springsource.org/spring-webflow/docs/2.3.x/reference/html/ch12s02.html
Write a Servlet extending HttpServlet that will
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)
servletConfig.getServletContext.getRealPath(“.”)
C:..Tomcatwebappssample.
doGet(HttpServletRequest, HttpServletResponse)
/resources/js/sample.js
C:..Tomcatwebappssample./resources/js/sample.js
I found this solution on the below URL. However, I haven’t tried this solution.