jun - 云代码空间
—— 相信 ,梦
package cn.itcast.web.filter; import java.io.IOException; import java.sql.SQLException; 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.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.domain.User; import cn.itcast.service.UserService; //完成自动登录 public class AutoLoginFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // 1.将请求与响应对象强制转换成http协议下的 HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; // 2.完成操作--自动登录 // 判断当前请求路径是否需要进行自动登录. String uri = request.getRequestURI(); String contextPath = request.getContextPath(); String path = uri.substring(contextPath.length()); // 获取访问的资源路径 if (path.equals("/demo1/login.jsp") || path.equals("/login")) { // 不需要进行自动登录 chain.doFilter(request, response); return; } else { // 判断用户没有登录 User u = (User) request.getSession().getAttribute("user"); if (u == null) { // 2.1.从http请求获取cookie Cookie[] cs = request.getCookies(); Cookie cookie = findCookieByName("username", cs); if (cookie != null) { // 可以进行自动登录 // 2.2得到cookie中username,password String username = cookie.getValue().split(":")[0]; String password = cookie.getValue().split(":")[1]; // 2.3.调用service进行登录操作 UserService service = new UserService(); try { User user = service.login(username, password); if (user != null) { // 2.4进行登录操作 request.getSession().setAttribute("user", user); chain.doFilter(request, response); return; } else { chain.doFilter(request, response); return; } } catch (SQLException e) { e.printStackTrace(); chain.doFilter(request, response); return; } } else { // 没cookie,放行 chain.doFilter(request, response); return; } } else { chain.doFilter(request, response); return; } } // 3.放行 // chain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { } public Cookie findCookieByName(String name, Cookie[] cs) { if (cs == null || cs.length == 0) { return null; } for (Cookie c : cs) { if (name.equals(c.getName())) { return c; } } return null; } }
<!-- 自动登录 --> <filter> <filter-name>autologin</filter-name> <filter-class>cn.itcast.web.filter.AutoLoginFilter</filter-class> </filter> <filter-mapping> <filter-name>autologin</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>