我正在尝试向servlet添加过滤器:
filter
配置如下:
@WebFilter(filterName = "AFilter",urlPatterns = "/*", servletNames = "AServlet")
public class AFilter implements Filter {
public void destroy() {
System.out.println("filter is dying");
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
chain.doFilter(req, resp);
System.out.println("filter is working");
}
public void init(FilterConfig config) throws ServletException {
System.out.println("filter is born");
}
我的AServlet
是这样的:
@WebServlet(name = "AServlet",urlPatterns = "/AServlet")
public class AServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("AServlet");
}
}
我正在使用注释来配置servlet和过滤器的映射,因此web.xml
文件为空,但问题是当我尝试运行Web应用程序时,我得到了这个输出:
AFilter is born
AFilter is working
AFilter is working
AFilter is working
似乎某些程序已调用AFilter
3次,但我无法确定哪个,以及当我尝试从网络浏览器访问Aservlet
时:http://localhost:80/AServlet
,我看到控制台是这样的:
AServlet
AFilter is working
这实在令我感到困惑,因为我似乎成功访问了AServlet
,AFilter
也正在履行职责。那么有人能告诉我什么是错的吗?提前致谢。 (顺便说一句:我使用的IDE是Intellij IDEA Ultimate版本)
答案 0 :(得分:0)
我在网上读了一些filter-servlet文章后问题解决了,问题是行:chain.doFilter(req,resp)
,我应该删除这行代码,否则filter会发送请求和响应到目的地无论如何我都去了。