过滤器(Filter)对登陆页面进行过滤验证



import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
public void destroy() {
}

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//不进行登陆无法访问其他页面
//ServletResponse类下面的子类HttpServletRequest中存在获取路径的方法getRequestURI
//首先对req进行强转
HttpServletRequest request = (HttpServletRequest) req;
//获取路径
String uri = request.getRequestURI();
//如果路径中存在这些就放行,注意:将jsp、css等路径也进行过滤,不然页面显示不全
if (uri.contains("login.jsp")
|| uri.contains("/loginServlet")
|| uri.contains("/checkCodeServlet")
|| uri.contains("/css/")
|| uri.contains("/fonts/")
|| uri.contains("/img/")
|| uri.contains("/js/")
) {
//放行
chain.doFilter(req, resp);


} else {
//获取session,看用户是否登陆
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
//登陆了进行放行操作
if (user != null) {
chain.doFilter(req, resp);

} else {
//没有登陆过跳转登录页面
request.getRequestDispatcher("/login.jsp").forward(request, resp);
}
}

}

public void init(FilterConfig config) throws ServletException {

}

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM