Java 之@WebFilter
一、参数说明
二、代码示例
package filter; 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.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebFilter(filterName = "login", urlPatterns = {"/admin/*"}, initParams = {@WebInitParam(name = "noLoginPath", value = "login.jsp;error.jsp;/login")}) public class JLoginFilter implements Filter{ private FilterConfig config; @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //String method = req.getParameter("method"); //System.out.println(method); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; // 检查地址是否不验证 String noLoginPaths = config.getInitParameter("noLoginPath"); //System.out.println("不验证地址:" + noLoginPaths); //System.out.println("当前访问地址:" + request.getRequestURL()); //System.out.println("当前访问地址getRequestURI:" + request.getRequestURI()); //System.out.println("queryString:" + request.getQueryString()); if (noLoginPaths != null) { String[] strArray = noLoginPaths.split(";"); for (int i = 0; i < strArray.length; i++) { if (strArray[i] == null || "".equals(strArray[i])) { continue; } if (request.getRequestURL().indexOf(strArray[i]) != -1) { chain.doFilter(req, resp); return; } } } //判断是否登录 Object user = request.getSession().getAttribute("admin"); if (user == null) { //chain.doFilter(req, resp); response.sendRedirect(request.getContextPath()+"/admin/login?method=Login"); } else { chain.doFilter(req, resp); } } @Override public void init(FilterConfig conf) throws ServletException { config = conf; } }