1
votes

I'm using Tomcat 7 to serve some JAXRS services. I also want to get a few static web pages to be served by the same application, using default servlet. This is how I define the mapping :

public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().getServletRegistrations().get("default").addMapping("/backoffice/*");
}

My problem is that the only way to access those static files is to use http://myserver.com/backoffice/index.html. I would like to access them just with http://myserver.com/backoffice I do not define any mapping in web.xml file, just my main JAXRS application. I've tried using welcome file list this way :

 <welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

I did not find any workaround on this problem, and the way I define the mapping to default servlet is the only one I found working.

Thanks for help.

2

2 Answers

1
votes

I can only think of two possibilities.

  1. Define a servlet mapping in the web.xml to the html file or
  2. Create a servlet, annotate it with @WebServlet and then in the doGet() method dispatch/redirect to the html file.

You could dynamically register the servlet if you prefered.

0
votes

What I ended with :

In my ServletContextListener, I added :

public void contextInitialized(ServletContextEvent sce) {
String name = "backoffice-filter";
sce.getServletContext().addFilter(name, new StaticRedirectionFilter(basePath, targetPath));
sce.getServletContext().getFilterRegistrations().get(name).addMappingForUrlPatterns(null, false, pathDepart);
sce.getServletContext().getServletRegistrations().get("default").addMapping("/backoffice/*");
}

The class StaticRedirectionFilter :

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String requestURI = request.getServletPath();
        if (requestURI.equals(basePath)) {
            HttpServletResponse response = (HttpServletResponse) res;
            response.sendRedirect(request.getContextPath() + targetPath);
        }
        else {
            chain.doFilter(req, res);
        }

    }

As Alex mentionned it, I could have done it with an annotation @WebFilter("/backoffice") abose the StaticRedirectionFilter class, but using the mapping in context seems better for reusability.

I also think it works before Servlet 3, even if I didn't try it.