首先我們看下 sendRedirect(重定向)與forworld(轉(zhuǎn)發(fā))的具體是指什么:
一個web資源受到客戶端請求后,通知服務器去調(diào)用另一個web資源進行處理,稱之為請求轉(zhuǎn)發(fā)。 一個web資源受到客戶端請求后,通知瀏覽器去調(diào)用另一個web資源進行處理,稱之為請求重定向。
根據(jù)字面意思上理解,重定向肯定是會重新走filter了,因為重定向是告知瀏覽器再次發(fā)出請求。而請求轉(zhuǎn)發(fā)則是服務器內(nèi)部的邏輯,它還會重新走filter嗎?
我們看下 正常的一個請求是怎么訪問到servelte的 ,下面我畫了個簡圖

到底是不是我們猜測的那樣呢?我們用代碼說話
首先創(chuàng)建自己的filter
public class CharsetEncodingFilter implements Filter {
private String encoding = null;
private ServletContext servletContext;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.encoding = filterConfig.getInitParameter("encoding");
this.servletContext = filterConfig.getServletContext();
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.setCharacterEncoding(encoding);
httpResponse.setCharacterEncoding(encoding);
servletContext.log("當前編碼已設置為:" + encoding);
// CharsetEncodingFilter -> FrontControllerServlet -> forward -> index.jsp
}
// 執(zhí)行過濾鏈
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
運行項目查看執(zhí)行結(jié)果:
日志輸出
三月 03, 2021 2:02:09 下午 org.apache.catalina.core.ApplicationContext log
三月 03, 2021 2:02:09 下午 org.apache.jasper.compiler.TldLocationsCache tldScanJar
發(fā)現(xiàn)并沒有咱們剛才打印的日志
servletContext.log("當前編碼已設置為:" + encoding);
這是未什么呢?
翻找servlet規(guī)范
[圖片上傳失敗...(image-ee5aab-1614751675752)]
文字太多 咱們只截圖部分說明哈,具體的文檔請翻閱《Java? Servlet 規(guī)范》3.1版本
根據(jù)文檔中我們發(fā)現(xiàn),設置filter是可以指定攔截的是什么類型的請求。
根據(jù)文檔,配置如下
<filter-mapping>
<filter-name>CharsetEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
再次打包運行,結(jié)果如下:
信息: 當前編碼已設置為:UTF-8
三月 03, 2021 2:02:09 下午 org.apache.jasper.compiler.TldLocationsCache tldScanJar
根據(jù)結(jié)果得知,無論是轉(zhuǎn)發(fā)和重定向都會根據(jù)是否配置了攔截的類型而進行攔截的。
git代碼:https://github.com/cuoduidui/geekbanglessons.git