web.xml配置
filter> <filter-name>AuthFilter</filter-name> <filter-class>com.hugui.drp.util.filter.AuthFilter</filter-class> </filter> <filter-mapping> <filter-name>AuthFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
AuthFilter.java
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.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class AuthFilter implements Filter { public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; System.out.println(req.getRequestURI()); System.out.println(req.getRequestURL()); String requestURI = req.getRequestURI().substring(req.getRequestURI().indexOf("/", 1), req.getRequestURI().length()); if(!"/login.jsp".equals(requestURI)){ //如果session没登录 HttpSession session = req.getSession(false); if(session == null || session.getAttribute("user_info") == null){ resp.sendRedirect(req.getContextPath() + "/login.jsp"); return ; } } //继续访问其他资源 chain.doFilter(req, resp); } public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } }