当您使用 url "/" 映射 spring-servlet(Spring) 时,所有请求都将重定向到 Spring-servlet。包括 .css & .js 等等。
尽管您找到了解决方案,但我为您提供了另一种我使用的替代方案。
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>static</servlet-name>
<servlet-class>StaticServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>static</servlet-name>
<url-pattern>/images/*</url-pattern>
<url-pattern>/css/*</url-pattern>
<url-pattern>/img/*</url-pattern>
<url-pattern>/js/*</url-pattern>
<url-pattern>/swf/*</url-pattern>
</servlet-mapping>
提供资源的静态 Servlet
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class StaticServlet extends HttpServlet {
private static final long serialVersionUID = 8458501870440200891L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String resourcePath = req.getServletPath() + req.getPathInfo();
String realPath = getServletContext().getRealPath(resourcePath);
FileInputStream fileInputStream = new FileInputStream(realPath);
try {
IOUtils.copy(fileInputStream, resp.getOutputStream());
} finally {
fileInputStream.close();
}
}
}