24H免费课程咨询  TEL:13401595960   QQ:1870218756  微信:13401595960(李老师)

东方博宜

网站首页 > 软件开发资讯 > Java开发

利用Cookie实现自动登陆(struts + hibernate版本)

2017-08-12 17:02:04 东方博宜 阅读

一、COOKIE:客户端缓存

session:服务器端缓存!

COOKIE的应用:自动登陆、存储小说看到的页码、存储电影看到的位置……

 

流程:

用户勾选“记住用户名密码” -> 登陆成功,向cookie存值 –> 访问main

 

后续访问index.jsp(登陆页面) -> 检查cookie的值 -> 如果cookie的值正确 -> 自动跳转main

 

问题:cookie存什么?

动态加密 + 不可逆加密:

内容:含有用户基本信息(识别是谁)和身份验证信息(如:密码)的信息

 

Base64encode(id=12&key=md5(id+password +系统的口令))

 

UserService

public class UserService {

 

         /**

          * 根据用户名密码判断登陆信息

          *

          * @param user

          * @return

          */

         public static User login(User user) {

                   User u = null;

                   if (user != null && user.getUsername() != null

                                     && user.getPassword() != null) {

                            Session session = HibernateSessionFactory.getSession();

                            Query query = session

                                               .createQuery("from User where username=? and password=?");

                            query.setParameter(0, user.getUsername());

                            query.setParameter(1, user.getPassword());

                            u = (User) query.uniqueResult();

 

                            HibernateSessionFactory.closeSession();

                   }

                   return u;

         }

        

        

         /**

          * 根据ID获取

          * @param uid

          * @return

          */

         public static Object getObj(Class c,int id){

                   Session session = HibernateSessionFactory.getSession();

                   Object obj = session.get(c, id);

 

                   HibernateSessionFactory.closeSession();

                   return obj;

         }

        

         /**

          * 获取properties文件的内容

          *

          * @param msgcode

          * @return

          */

         public static String getMessage(String msgcode) {

                   String r = "";

 

                   try {

                            InputStream is = UserService.class.getClassLoader()

                                               .getResourceAsStream("keys.properties");

                            Properties pro = new Properties();

                            pro.load(is);

                            r = pro.getProperty(msgcode);

                   } catch (Exception e) {

                            e.printStackTrace();

                   }

 

                   return r;

         }

        

         /**

          * MD5加密

          * @param str

          * @return

          */

         public static String md5(String str){

                   String s = null;

                   try {

                            MessageDigest md = MessageDigest.getInstance("MD5");

                            BASE64Encoder bs = new BASE64Encoder();

                            s = bs.encode(md.digest(str.getBytes()));

                   } catch (Exception e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                   return s;

         }

        

        

         /**

          * 对字符串进行64位编码

          * @param s

          * @return

          */

         public static String encode(String s){

                   String r = null;

                  

                   if(s != null){

                            BASE64Encoder e = new BASE64Encoder();

                            r = e.encode(s.getBytes());

                   }

                  

                   return r;

         }

        

         /**

          * 解码

          * @param s

          * @return

          */

         public static String decode(String s){

                   String r = null;

                  

                   if(s != null){

                            try{

                                     BASE64Decoder d = new BASE64Decoder();

                                     byte[] b = d.decodeBuffer(s);

                                     r = new String(b);

                            }catch(Exception e){

                                     e.printStackTrace();

                            }

                   }

                  

                   return r;

         }

        

         /**

          * 存储cookie的内容

          */

         public static void addCookie(int id,String password){

                  String value = encode("id=" + id + "&key=" + md5(id + password + getMessage("m")));

                   Cookie cookie = new Cookie("crmautologin",value);

                   cookie.setMaxAge(3600 * 24 * 365 * 10);

                   cookie.setPath("/");

                  

                   //存储cookie

                   ServletActionContext.getResponse().addCookie(cookie);

         }

        

    /**

     * 检查自动登录的cookie是否正确,正确,返回该用户的所有信息,错误,返回null

     *

     * @return

     */

    public static User checkLoginCookie() {

       User user = null;

 

       // 检测是否有cookie,如果有,检测cookie是否正确

       Cookie[] cookies = ServletActionContext.getRequest().getCookies();

       if (cookies != null) {

           for (Cookie cookie : cookies) {

              // 如果是自动登录的信息

              if (cookie.getName() != null

                     && cookie.getName().equals("crmautologin")) {

                  String value = cookie.getValue();

                  value = value != null ? decode(value) : null;

                  // id=1&key=uCRWLK6X7ncYtnrzJyQaQA==

                  Map params = getParameters(value);

                  // 根据ID获取用户

                  if (params.get("id") != null) {

                     int id = Integer.parseInt((String) params.get("id"));

                     User u = (User) getObj(User.class, id);

                     if (u != null) {

                         String thiskey = md5(u.getUid() + u.getPassword()

                                + getMessage("m"));// 我们认为正确的信息

                         String key = (String) params.get("key");// cookiekey

                         // 比对key是否正确

                         if (key != null && key.equals(thiskey)) {

                             user = u;

                         }

                     }

                  }

              }

           }

       }

 

       return user;

    }      

        

        

         /**

          * 将类似:id=1&key=uCRWLK6X7ncYtnrzJyQaQA==,解析回Map

          * @param url

          * @return

          */

         public static Map getParameters(String url){

                   Map map = new HashMap();

                  

                   if(url != null){

                       String[] params = url.split("&");

                       //id=1

                       for(int i = 0;i < params.length;i++){

                                //按照第一个=截取两边的内容

                                String key = params[i].substring(0, params[i].indexOf("="));

                                String value = params[i].substring(params[i].indexOf("=") + 1);

                                map.put(key, value);

                       }

                      

                   }

                   return map;

         }

        

         public static void main(String[] args) {

                   String s = "aWQ9MSZrZXk9dUNSV0xLNlg3bmNZdG5yekp5UWFRQT09";

                   String s2 = decode(s);

                   System.out.println(s2);

                   System.out.println(md5(1 + "333testcookie"));

                  

                   Map map = getParameters("id=1&key=uCRWLK6X7ncYtnrzJyQaQA==");

                   System.out.println(map);

         }

        

}

 

 

 

index.jsp

     <tr>

       <td colspan="2">

          <input type="checkbox" name="remember" value="Y">记住用户名密码

       <br />

       <input type="submit" value="提交"/>

       <input type="submit" value="重置"/>

       </td>

     </tr>

 

UserAction:

/**

 * 中转控制层

 */

public class UserAction {

 

         private User user;

        

         /**

          * 登陆

          * @return

          */

         public String login(){

                   String r = "input";

                   User res = UserService.login(user);

                   //如果登陆成功

                   if(res != null){

                            r = "success";

                            HttpServletRequest request = ServletActionContext.getRequest();

                            request.getSession().setAttribute("usermsg", res);

                           

                            //判断是否需要记住用户名密码

                            if(request.getParameterValues("remember") != null){

                                     UserService.addCookie(res.getUid(), res.getPassword());

                            }

                   }

                  

                   return r;

         }

 

         public User getUser() {

                   return user;

         }

 

         public void setUser(User user) {

                   this.user = user;

         }

        

        

}

 

AutoLoginFilter

/**

 * 判断用户是否需要自动登陆

 */

public class AutoLoginFilter implements Filter{

 

         public void destroy() {

                  

         }

 

         public void doFilter(ServletRequest res, ServletResponse req,

                            FilterChain chain) throws IOException, ServletException {

                   System.out.println("访问登陆页面!");

                  HttpServletRequest request = (HttpServletRequest) res;

                   HttpServletResponse response = (HttpServletResponse) req;

                  

                   User user = UserService.checkLoginCookie();

                  

                   //如果要自动登陆

                   if(user != null){

                            request.getSession().setAttribute("usermsg", user);

                            request.getRequestDispatcher("main.jsp").forward(request, response);

                   }else{

                            chain.doFilter(res, req);

                   }

                  

         }

 

         public void init(FilterConfig arg0) throws ServletException {

                  

         }

 

        

}

 

web.xml

  <!-- 过滤登陆页面的访问 -->

  <filter>

     <filter-name>AutoLoginFilter</filter-name>

     <filter-class>com.crm.filter.AutoLoginFilter</filter-class>

  </filter> 

 

  <filter-mapping>

     <filter-name>AutoLoginFilter</filter-name>

     <url-pattern>/index.jsp</url-pattern>

  </filter-mapping>

 

图片.png

Powered by 东方博宜教育咨询江苏有限公司  ©2008-2017 www.czos.cn