SSO 基于Cookie+fliter实现单点登录 实例解析(一)(二)

2015-01-27 14:08:02 · 作者: · 浏览: 76
.equals() && pwd.startsWith(pwd)){ System.err.println(登录成功。。。。。); forward = /jsps/welcome.jsp; //无论如何,都要设置cookie,如果没有选择自动登录,则只在当前页面的跳转时有效,否则设置有效期间为7天。 Cookie cookie = new Cookie(autologin,nm+@+pwd); cookie.setPath(/); //如果路径为/则为整个tomcat目录有用 cookie.setDomain(.itcast.com); //设置对所有*.itcast.com为后缀的域名效 if(chk!=null){ int time = 1*60*60*24*7; //1秒*60=1分*60分=1小时*24=1天*7=7天 cookie.setMaxAge(time); } resp.addCookie(cookie); req.getSession().setAttribute(user, nm); }else{ System.err.println(登录不成功。。。。。。); } req.getRequestDispatcher(forward).forward(req, resp); } }

3、自动登录的Filter程序如下:

/** * 自动登录 */ public class AutoLogin implements Filter { public void destroy() {} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { System.err.println(开始自动登录验证.....);//此类中应该对登录的servlet直接放行。根据判断url决定。 HttpServletRequest requ = (HttpServletRequest) req; HttpSession s = requ.getSession(); if (s.getAttribute(user) != null) {//如果用户已经登录则直接放行 System.err.println(用户已经登录,没有必须要再做自动登录。。。。); } else { Cookie[] cookies = requ.getCookies(); if (cookies != null) { for (Cookie ck : cookies) { if (ck.getName().equals(autologin)) {// 是否是自动登录。。。。 System.err.println(自动登录成功。。。。。); String val = ck.getValue(); String[] vals = val.split(@); s.setAttribute(user, vals[0]); } } } } chain.doFilter(req, resp); } public void init(FilterConfig filterConfig) throws ServletException {} } 


4、正常退出的Servlet如下

/** * 安全退出删除Cookie */ public class LoginOutServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession s = req.getSession(); //获取Session Cookie cookie = new Cookie(autologin,);//必须声明一个完全相同名称的Cookie cookie.setPath(/);//路径也要完全相同 cookie.setDomain(.itcast.com);//域也要完全相同 cookie.setMaxAge(0);//设置时间为0,以直接删除Cookie resp.addCookie(cookie); s.removeAttribute(user); System.err.println(安全退出。。。。。); resp.sendRedirect(req.getContextPath()+/index.jsp); } } 

?

这种是基于最简单的方式实现的单点登录,效果图在下篇博客中的

?

使用基于CAS单点登录流程实例与效果图

?

?