废话也不多说直接上代码吧!
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 LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpServletResponse servletResponse = (HttpServletResponse) response;
HttpSession session = servletRequest.getSession();
String path = servletRequest.getContextPath();
String user= (String) session
.getAttribute("user");
// 判断如果没有取到员工信息,就跳转到登陆页面
if (user!= null
|| servletRequest.getServletPath().indexOf("mian/login") > 0 //不过滤登录页面
|| servletRequest.getServletPath().indexOf("captcha/image") > 0 //不过滤登图片验证码
|| servletRequest.getServletPath().indexOf("mobileauth/login") > 0 //不过滤登录的请求路径
|| servletRequest.getServletPath().endsWith(".css") //不过滤CSS养生
|| servletRequest.getServletPath().endsWith(".js") //不过滤js文件
|| servletRequest.getServletPath().contains(".jsp")) { // 过滤.jsp为后缀的页面。如果是jsp页面去掉此行即可
// 已经登陆,继续此次请求
chain.doFilter(request, response);
} else {
// 没有登录任何操作跳转到登录页面
servletResponse.sendRedirect(path+"/mian/login");
}
}
@Override
public void destroy() {
}
}
然后就是在web.xml 里面配置过滤器
<!-- 配置登陆过滤器 -->
<filter>
<filter-name>login</filter-name>
<filter-class>com.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>