发表于: 2017-11-08 23:03:31

1 660


【今日完成】

今天把自己模块的东西剩下的写了。主要是一个登陆接口

@RequestMapping(value = "a/login",method = RequestMethod.POST) // @RequestMapping 注解可以用指定的URL路径访问本控制层
public String login(Model model, HttpServletResponse response, HttpServletRequest request,String adminName,String password) {

if(null == adminName||null == password){
model.addAttribute("code",-200000);
     model.addAttribute("specialmessage","参数缺失");
     return "data/json";
  }
try {
Map<String, Object> param = DynamicUtil.getAdmin(adminName);
     List<Long> ids = adminService.getIdsByDynamicCondition(Admin.class, param, 0, 1);
     List<Admin> adminsList = adminService.getObjectsByIds(ids);
     if(adminsList.size() >0) {
Admin admin = adminsList.get(0);
        if (admin != null){
log.info(admin.getAdminName());
           log.info(admin.getAdminPassword());
           log.info(password);
           if (admin.getAdminPassword().equals(password)) {
log.info("enter");
              Cookie cookie =new Cookie("token","aaa");//生成cookie,值为token字符串
              cookie.setMaxAge(60*60*24);//过期时间为1
              cookie.setPath("/");
              response.addCookie(cookie);
              System.out.println("设置cookie"+cookie.getName());
              model.addAttribute("code",0);
              model.addAttribute("specialmessage","登录成功");
              return "data/json";
           }
}
}

}catch (Exception e){
e.printStackTrace();
  }
model.addAttribute("code",-5002);
  model.addAttribute("specialmessage","账号或密码错误");
  return "data/json";

}

登陆成功的话会保存一个特定的Cookie在用户电脑里,

然后配置一下拦截器。

每次收到/a/u的请求之后,会调用拦截器,看一看有没有的cookie

下面是拦截器代码:

/*
* 拦截器需要实现HandlerInterceptor接口
* 接口有三种方法,preHandlepostHandleafterCompletion
* 三种方法区别是执行的时间,这里我只对preHandle做了配置
*
* */
public class LoginInterceptor implements HandlerInterceptor {
private static final Log log = LogFactory.getLog(LoginInterceptor.class);
   static int j =0;
   public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//拿到所有的cookie
       Cookie[] cookie = httpServletRequest.getCookies();

       log.info("这是拦截器");


       //遍历一遍cookie,只要中间有名字为"token"的,就放行,否则就拦截
       //因为只有在账号密码输入正确的时候才会生成名为"token"cookie
       for(int i=0;i<cookie.length;i++){

if(cookie[i].getName().equals("token")&&cookie[i].getValue().equals("aaa")){
j =i;
               log.info("放行");
               return  true;
           }
}
httpServletResponse.sendRedirect("/a/login");
           return false;

   }

在SpringMVC中配置:


这样一个基本的管理员拦截功能就实现了。

但是比较low

我准备看看shiro,看能不能用在自己的项目中


【今日收获】

完成了登录接口


【明日计划】

思考有没有更好的方式实现,有的话就重写一下代码


返回列表 返回列表
评论

    分享到