好吧,直接點: 我創建 - 用Eclipse - 兩個過濾器(Filter1和Filter2)和一個servlet(DisplayHeader)來查看過濾器的執行順序。 我使用Tomcat 8.5作爲目標運行時。過濾順序和web.xml內容
新建/動態Web項目/ 與上下文根/ 並檢查「生成的web.xml delpoyment描述」
過濾器1版畫「我過濾器1」時,它的執行,我「鏈接」它到特定的servlet「DisplayHeader」。 Filter2它是2的兄弟,而不是1. DisplayHeader servlet映射到/ DisplayHeader。
下面是爲了清楚
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
@WebFilter(
urlPatterns = {"/Filter1"},
servletNames = {"DisplayHeader"}
)
public class Filter1 implements Filter {
/**
* Default constructor.
*/
public Filter1() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
System.out.println("I'm Filter 1");
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
那麼過濾器1的代碼,當我運行在Tomcat(Tomcat的V8.5)小服務程序將打印
I'm Filter 1
I'm Filter 2
這意味着過濾器1被過濾器2之前執行。
,我讀了執行的過濾器的訂單來自於web.xml文件映射順序, 所以我希望能夠找到在web.xml文件中像
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/DisplayHeader</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Filter2</filter-name>
<url-pattern>/DisplayHeader</url-pattern>
</filter-mapping>
,我應該改變的地方爲了...
的問題是:當我打開我的項目的web.xml文件(從Project Explorer,見下圖)文件,我只是看到這一點:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SetFilterOrder</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
web.xml location in the explorer
我只是缺少正確的web.xml文件路徑或此web.xml是使用「生成web.xml delpoyment描述符」選項的結果?
謝謝。看起來很奇怪,如果你使用註釋是不可能的。那麼,就這樣吧。 – ptr87max
我同意它似乎確實存在差距,他們應該修復。你有沒有考慮過使用Spring MVC而不是JEE?在Spring中,你可以在代碼中做到這一點,沒有web.xml。 –
我是一個真正的紐比在這件事。我只是在網上查看servlets教程,並且也彈出了過濾主題。 如果我將永遠需要深入探討這個問題,我會記住你的建議:) – ptr87max