欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaWeb使用Session和Cookie实现登录认证

程序员文章站 2024-03-03 19:29:34
后台管理页面往往需要登录才可以进行操作,这时就需要seession来记录登录状态 要实现起来也是非常简单,只需要自定义一个handlerinterceptor就行了...

后台管理页面往往需要登录才可以进行操作,这时就需要seession来记录登录状态

要实现起来也是非常简单,只需要自定义一个handlerinterceptor就行了

自定义的handlerinterceptor也只有短短几行代码

public class logininterceptor implements handlerinterceptor {

  @override
  public void aftercompletion(httpservletrequest request,
                httpservletresponse response, object obj, exception err)
      throws exception {
  }

  @override
  public void posthandle(httpservletrequest request, httpservletresponse response,
              object obj, modelandview mav) throws exception {

  }

  @override
  public boolean prehandle(httpservletrequest request, httpservletresponse response,
               object obj) throws exception {
    //获取session里的登录状态值
    string str = (string) request.getsession().getattribute("islogin");
    //如果登录状态不为空则返回true,返回true则会执行相应controller的方法
    if(str!=null){
      return true;
    }
    //如果登录状态为空则重定向到登录页面,并返回false,不执行原来controller的方法
    response.sendredirect("/backend/loginpage");
    return false;
  }
}

controller代码

@controller
@requestmapping("/backend")
public class backendcontroller {

  @requestmapping(value = "/loginpage", method = {requestmethod.get})
  public string loginpage(httpservletrequest request,string account, string password){
    return "login";
  }

  @requestmapping(value = "/login", method = {requestmethod.post})
  public string login(httpservletrequest request,redirectattributes model, string account, string password){
    //验证账号密码,如果符合则改变session里的状态,并重定向到主页
    if ("jack".equals(account)&&"jack2017".equals(password)){
      request.getsession().setattribute("islogin","yes");
      return "redirect:indexpage";
    }else {
      //密码错误则重定向回登录页,并返回错误,因为是重定向所要要用到redirectattributes
      model.addflashattribute("error","密码错误");
      return "redirect:loginpage";
    }
  }
  //登出,移除登录状态并重定向的登录页
  @requestmapping(value = "/loginout", method = {requestmethod.get})
  public string loginout(httpservletrequest request) {
    request.getsession().removeattribute("islogin");
    return "redirect:loginpage";
  }
  @requestmapping(value = "/indexpage", method = {requestmethod.get})
  public string indexpage(httpservletrequest request){
    return "index";
  }

}

spring的配置

  <!--省略其他基本配置-->

  <!-- 配置拦截器 -->
  <mvc:interceptors>
    <!-- 配置登陆拦截器 -->
    <mvc:interceptor>
      <!--拦截后台页面的请求-->
      <mvc:mapping path="/backend/**"/>
      <!--不拦截登录页和登录的请求-->
      <mvc:exclude-mapping path="/backend/loginpage"/>
      <mvc:exclude-mapping path="/backend/login"/>
      <bean class="com.ima.interceptor.logininterceptor"></bean>
    </mvc:interceptor>
  </mvc:interceptors>

一个简单的session实现登录认证系统就这样完成了,如果想登录状态退出浏览器后仍保留一段时间的可以将session改为cookie

一般情况下我们都会使用cookie

cookie和session的方法差不多

使用cookie的自定义handlerinterceptor

public class logininterceptor implements handlerinterceptor {

  @override
  public void aftercompletion(httpservletrequest request,
                httpservletresponse response, object obj, exception err)
      throws exception {
  }

  @override
  public void posthandle(httpservletrequest request, httpservletresponse response,
              object obj, modelandview mav) throws exception {

  }

  @override
  public boolean prehandle(httpservletrequest request, httpservletresponse response,
               object obj) throws exception {
//    获取request的cookie
    cookie[] cookies = request.getcookies();
    if (null==cookies) {
      system.out.println("没有cookie==============");
    } else {
//      遍历cookie如果找到登录状态则返回true执行原来controller的方法
      for(cookie cookie : cookies){
        if(cookie.getname().equals("islogin")){
          return true;
        }
      }
    }
//    没有找到登录状态则重定向到登录页,返回false,不执行原来controller的方法
    response.sendredirect("/backend/loginpage");
    return false;
  }
}

controller的变化也不大

@controller
@requestmapping("/backend")
public class backendcontroller {

  @requestmapping(value = "/loginpage", method = {requestmethod.get})
  public string loginpage(httpservletrequest request, string account, string password) {
    return "login";
  }

  @requestmapping(value = "/login", method = {requestmethod.post})
  public string login(httpservletrequest request, httpservletresponse response, redirectattributes model, string account, string password) {
    if ("edehou".equals(account) && "aidou2017".equals(password)) {
      cookie cookie = new cookie("islogin", "yes");
      cookie.setmaxage(30 * 60);// 设置为30min
      cookie.setpath("/");
      response.addcookie(cookie);
      return "redirect:indexpage";
    } else {
      model.addflashattribute("error", "密码错误");
      return "redirect:loginpage";
    }
  }

  @requestmapping(value = "/logout", method = {requestmethod.get})
  public string loginout(httpservletrequest request, httpservletresponse response) {
    cookie[] cookies = request.getcookies();
    for (cookie cookie : cookies) {
      if (cookie.getname().equals("islogin")) {
        cookie.setvalue(null);
        cookie.setmaxage(0);// 立即销毁cookie
        cookie.setpath("/");
        response.addcookie(cookie);
        break;
      }
    }
    return "redirect:loginpage";
  }

  @requestmapping(value = "/indexpage", method = {requestmethod.get})
  public string indexpage(httpservletrequest request) {
    return "index";
  }

}

spring的配置和之前的一模一样

注意

这里只是演示,建议在实际项目中cookie的键和值要经过特殊处理,否则会引发安全问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。