search
HomeJavajavaTutorialJavaWeb uses Session and Cookie to implement login authentication code example sharing

This article mainly introduces JavaWeb to use Session and Cookie to implement login authentication. It has certain reference value. Interested friends can refer to it.

The background management page often requires login before operation. In this case, Seession is needed to record the login status

It is also very simple to implement, just need Just customize a HandlerInterceptor

The customized HandlerInterceptor only has a few lines of code

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 code

@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 configuration

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

  <!-- 配置拦截器 -->
  <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>

A simple Session implementation login authentication system is completed. If you want the login status to remain for a period of time after exiting the browser, you can change the Session to Cookie

Under normal circumstances we will use Cookie

Cookie and Session methods are similar

Using Cookie's custom 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 has not changed much either

@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";
  }

}

The configuration of spring is exactly the same as before

Note

This is just a demonstration , it is recommended that the key and value of Cookie should be specially processed in actual projects, otherwise it will cause security issues

The above is the detailed content of JavaWeb uses Session and Cookie to implement login authentication code example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
SpringBoot Session怎么设置会话超时SpringBoot Session怎么设置会话超时May 15, 2023 pm 02:37 PM

问题发现springboot项目生产session-out超时问题,描述下问题:在测试环境通过改动application.yaml配置session-out,经过设置不同时间验证session-out配置生效,于是就直接设置了过期时间为8小时发布到了生产环境。然而中午接到客户反应项目过期时间设置较短,半小时不操作就会话过期需要反复登陆。解决处理开发环境:springboot项目内置Tomcat,所以项目中application.yaml配置session-out是生效的。生产环境:生产环境发布是

如何分析Java Web安全中的代码审计如何分析Java Web安全中的代码审计May 16, 2023 am 08:04 AM

一、JavaWeb安全基础1.何为代码审计?通俗的说Java代码审计就是通过审计Java代码来发现Java应用程序自身中存在的安全问题,由于Java本身是编译型语言,所以即便只有class文件的情况下我们依然可以对Java代码进行审计。对于未编译的Java源代码文件我们可以直接阅读其源码,而对于已编译的class或者jar文件我们就需要进行反编译了。Java代码审计其本身并无多大难度,只要熟练掌握审计流程和常见的漏洞审计技巧就可比较轻松的完成代码审计工作了。但是Java代码审计的方式绝不仅仅是使

php session刷新后没有了怎么办php session刷新后没有了怎么办Jan 18, 2023 pm 01:39 PM

php session刷新后没有了的解决办法:1、通过“session_start();”开启session;2、把所有的公共配置写在一个php文件内;3、变量名不能和数组下标相同;4、在phpinfo里面查看session数据的存储路径,并查看该文件目录下的sessio是否保存成功即可。

session php默认失效时间是多少session php默认失效时间是多少Nov 01, 2022 am 09:14 AM

session php默认失效时间是1440秒,也就是24分钟,表示客户端超过24分钟没有刷新,当前session就会失效;如果用户关闭了浏览器,会话就会结束,Session就不存在了。

PHP如何在多个文件中正确地读取和写入Session数据PHP如何在多个文件中正确地读取和写入Session数据Mar 23, 2023 am 11:12 AM

当您在使用PHP会话(Session)时,有时会发现Session在一个文件中可以正常读取,但在另一个文件中却无法读取。这可能会让您感到困惑,因为会话数据应该可以在整个应用程序中共享。本文将解释如何在多个文件中正确地读取和写入PHP会话数据。

Redis的共享session应用如何实现短信登录Redis的共享session应用如何实现短信登录Jun 03, 2023 pm 03:11 PM

1.基于session实现短信登录1.1短信登录流程图1.2实现发送短信验证码前端请求说明:说明请求方式POST请求路径/user/code请求参数phone(电话号码)返回值无后端接口实现:@Slf4j@ServicepublicclassUserServiceImplextendsServiceImplimplementsIUserService{@OverridepublicResultsendCode(Stringphone,HttpSessionsession){//1.校验手机号if

Springboot2 session设置超时时间无效怎么解决Springboot2 session设置超时时间无效怎么解决May 22, 2023 pm 01:49 PM

问题:今天项目中遇到了一个设置时间超时的问题,按SpringBoot2的application.properties更改一直不生效。解决方案:server.*属性用于控制SpringBoot使用的嵌入式容器。SpringBoot将使用ServletWebServerFactory实例之一创建servlet容器的实例。这些类使用server.*属性来配置受控的servlet容器(tomcat,jetty等)。当应用程序作为war文件部署到Tomcat实例时,server.*属性不适用。它们不适用,

JavaScript和PHP的cookie之间有哪些区别?JavaScript和PHP的cookie之间有哪些区别?Sep 02, 2023 pm 12:29 PM

JavaScriptCookie使用JavaScriptcookie是记住和跟踪偏好、购买、佣金和其他信息的最有效方法。更好的访问者体验或网站统计所需的信息。PHPCookieCookie是存储在客户端计算机上的文本文件并保留它们用于跟踪目的。PHP透明地支持HTTPcookie。JavaScriptcookie如何工作?您的服务器将一些数据发送到访问者的浏览器cookie的形式。浏览器可以接受cookie。如果存在,它将作为纯文本记录存储在访问者的硬盘上。现在,当访问者到达站点上的另一个页面时

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools