My Servlet(在Jetty上運行)還應該部署靜態目錄中的靜態內容。通過默認servlet在Jetty中提供靜態資源
目錄結構:
/
- static/
- [static files]
- WEB-INF/
- [my servlet .class files and the web.xml]
我的web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<filter>
<filter-name>filter</filter-name>
<filter-class>com.example.StaticFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
我主要的Servlet文件:
@WebServlet("/*")
public class SampleClass extends HttpServlet {
//Code
}
我的過濾器:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class StaticFilter implements Filter {
@Override
public void init(FilterConfig fc) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String path = req.getRequestURI().substring(req.getContextPath().length());
if (path.startsWith("/static")) {
request.getRequestDispatcher(path).forward(request, response);
} else {
chain.doFilter(request, response);
}
}
}
現在,如果我調用/static/style.css,我想從/靜態獲取該文件,而不是重定向到該servlet。
服務器:碼頭9.1.0 RC1
你有一個HttpServlet的定義爲過濾? –
對不起,我忘記了過濾器的代碼,編輯了問題 –
您知道靜態內容將由DefaultServlet根據servlet規範提供嗎? –