首先实现Filter接口(该实例是用于判断session中是否存在用户)
package com.xinzhi.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.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // 1. 获取请求资源,截取 String uri = request.getRequestURI(); // /emp_sys/login.jsp // 截取 【login.jsp或login】 String requestPath = uri.substring(uri.lastIndexOf("/") + 1, uri .length()); // 2. 判断: 先放行一些资源:/login.jsp、/login if ("LoginServlet".equals(requestPath) || "login.jsp".equals(requestPath)) { // 放行 chain.doFilter(request, response); } else { // 3. 对其他资源进行拦截 // 3.1 先获取Session、获取session中的登陆用户(loginInfo) HttpSession session = request.getSession(false); // 判断 if (session != null) { Object obj = session.getAttribute("adminname"); // 3.2如果获取的内容不为空,说明已经登陆,放行 if (obj != null) { // 放行 uri = requestPath; // chain.doFilter(request, response); } else { // 3.3如果获取的内容为空,说明没有登陆; 跳转到登陆 uri = "jsp/login.jsp"; } } else { // 肯定没有登陆 uri = "jsp/login.jsp"; } request.getRequestDispatcher(uri).forward(request, response); } } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
然后要在web.xml配置文件中指定相关信息
<filter> <filter-name>filter</filter-name> <filter-class>com.xinzhi.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
时间: 2024-10-12 10:13:53