過濾器(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