JSP中Filter无效问题

写了个登录过滤器,用于阻止未登录用户访问网站页面,刚开始的写法如下:
@WebFilter(filterName = "/LoginFilter")
public class LoginFilter implements Filter {
	
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		String servletPath = httpRequest.getServletPath();
		if (servletPath.equals("/login.jsp")) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		HttpSession session = httpRequest.getSession();
		if (session.getAttribute("username") == null) {
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
		} else
			chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}


这里采用了Annotation的方法,避免了修改web.xml,但是却完全没有效果,百思不得其解,后来查阅了相关文档,发现需要将:
@WebFilter(filterName = "/LoginFilter")

修改为:
@WebFilter(filterName = "/LoginFilter", urlPatterns = {"/*"})

即可。
urlPatterns表示需要过滤的页面,如果不添加该字段,默认不对任何网页进行过滤。

你可能感兴趣的:(filter)