Servlet for serving static content

前端 未结 14 2039
天命终不由人
天命终不由人 2020-11-22 06:02

I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structur

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 06:32

    I did this by extending the tomcat DefaultServlet (src) and overriding the getRelativePath() method.

    package com.example;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.catalina.servlets.DefaultServlet;
    
    public class StaticServlet extends DefaultServlet
    {
       protected String pathPrefix = "/static";
    
       public void init(ServletConfig config) throws ServletException
       {
          super.init(config);
    
          if (config.getInitParameter("pathPrefix") != null)
          {
             pathPrefix = config.getInitParameter("pathPrefix");
          }
       }
    
       protected String getRelativePath(HttpServletRequest req)
       {
          return pathPrefix + super.getRelativePath(req);
       }
    }
    

    ... And here are my servlet mappings

    
        StaticServlet
        com.example.StaticServlet
        
            pathPrefix
            /static
               
    
    
    
        StaticServlet
        /static/*
      
    

提交回复
热议问题