码迷,mamicode.com
首页 > 其他好文 > 详细

简单的看一下cookie的用法、同时谈谈代码规范

时间:2017-09-22 13:08:57      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:getname   case   lan   color   ddl   客户端   logger   exist   style   

业务需求:用户登录需要输入验证码

单机版可以采用session存储,在集群环境下不行,

ok ,验证码生成后加密同时生成cookie ,推送至客户端。用户登录提交,后台通过request取出cookies与输入值做检验

public class CookieUtil {
    
     private final static String LOGIN_COOKIE           = "test";
     private final static String LOGIN_PATH          = "/";
     
     private static Logger log = LoggerFactory.getLogger(CookieUtil .class);
     
     public static void addLoginCode(HttpServletRequest request,
                      HttpServletResponse response, String code) {

         if (StringUtil.isBlank(code)) {
            return;
         }
       
         code = Md5Util.getMd5(code.toLowerCase()).toLowerCase();
         
         Cookie cookie = new Cookie(LOGIN_COOKIE, code);
         cookie.setPath(LOGIN_PATH);
         cookie.setMaxAge(-1);
       
         response.addCookie(cookie);
         
         log.debug("create login code to cookie success, the cookie of value is:{}", cookie.getValue());
     }
     
     public static Boolean validate(HttpServletRequest request,
            HttpServletResponse response, String code){
         
         if (StringUtil.isBlank(code)) {
             return Boolean.FALSE;
         }
         
         Cookie[] cookies = request.getCookies();
         if (null == cookies || cookies.length < 1) {
             log.debug("no cookies exist");
             return Boolean.FALSE;
         }
         
         code = Md5Util.getMd5(code.toLowerCase()).toLowerCase();
         
         for (Cookie thisCookie : cookies) {
             if (LOGIN_COOKIE.equals(thisCookie.getName()) && code.equals(thisCookie.getValue())) {
                  log.debug("login code validate success, the value of cookie is:{}", thisCookie.getValue());
                     return Boolean.TRUE;
             }
         }
        log.debug("login code validate failed");
        
        return Boolean.FALSE;
     }
     
    
}

 技术我就不多说了,如还有疑问可以参看其他博客

下面我想说一下代码规范:

 

在说代码规范之前,我稍微解释下,上面的代码是我经过了两轮的优化。

举个例子:

if (StringUtil.isBlank(code)) {
    return;
}
code = Md5Util.getMd5(code.toLowerCase()).toLowerCase();

修改之前是:

if (StringUtil.isNotBlank(code)) {
   code = Md5Util.getMd5(code.toLowerCase()).toLowerCase();
}else{
   return; 
}

 ok,逻辑没有问题,不过,代码不够精简

当然还有其他问题,

比如 判断 cookie为空,从代码美观角度上考虑 应该是  cookie == null 而不是  null == cookie

比如 常量与对象的属性比较是否相等,常量尽量前置、

and so on...

 

总结

1.代码精简,易读;

2.嵌套不宜过深;

3.字符串比较 常量尽量放在equal之前;

4.一个方法快中的代码要有 块的概念。块与块之间用空行来分割;

5.日志的规范,尽量使用英文,避免线上有时产生的中文乱码

简单的看一下cookie的用法、同时谈谈代码规范

标签:getname   case   lan   color   ddl   客户端   logger   exist   style   

原文地址:http://www.cnblogs.com/sunshine798798/p/7574253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!