C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

How to access static resources when using default servlet?

0 votes
30 views
Hi i have a problem i want to send all my request to one spring servlet

<servlet>      
  <servlet-name>home</servlet-name>        
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     
</servlet>  
<servlet-mapping>      
  <servlet-name>home</servlet-name>        
  <url-pattern>/*</url-pattern>     
</servlet-mapping>
but this mapping stops the access to static files like images etc i have put them all in /res/....... folder

please help me how can i make this work i am using this on google app engine.
asked Jan 29, 2014 by john Guru (27,140 points)

1 Answer

0 votes

 

 
Map the controller servlet on a more specific url-pattern like /pages/*, put the static content in a specific folder like /static and create a Filter listening on /* which transparently continues the chain for any static content and dispatches requests to the controller servlet for other content.
 
In a nutshell:
 
<filter>
    <filter-name>filter</filter-name>
    <filter-class>com.example.Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
 
<servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>com.example.Controller</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>controller</servlet-name>
    <url-pattern>/pages/*</url-pattern>
</servlet-mapping>
with the following in filter's doFilter():
 
HttpServletRequest req = (HttpServletRequest) request;
String path = req.getRequestURI().substring(req.getContextPath().length());
 
if (path.startsWith("/static")) {
    chain.doFilter(request, response); // Goes to default servlet.
} else {
    request.getRequestDispatcher("/pages" + uri).forward(request, response);
}
No, this does not end up with /pages in browser address bar. It's fully transparent. You can if necessary make "/static" and/or "/pages" an init-param of the filter.
 
answered Jan 29, 2014 by keem Expert (13,240 points)

Related questions

0 votes
2 answers 21 views
21 views asked Jan 20, 2014 by john Guru (27,140 points)
0 votes
1 answer 5 views
5 views asked Jan 4, 2014 by keem Expert (13,240 points)
0 votes
1 answer 10 views
10 views asked Jan 3, 2014 by sara Guru (24,570 points)
0 votes
1 answer 31 views
31 views asked Jan 2, 2014 by sara Guru (24,570 points)
0 votes
1 answer 26 views
26 views asked Jan 21, 2014 by john Guru (27,140 points)
...