Home > Java > javaTutorial > body text

JavaWeb uses Session and Cookie to implement login authentication code example sharing

黄舟
Release: 2017-03-18 10:17:32
Original
1477 people have browsed it

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;
  }
}
Copy after login

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

}
Copy after login

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>
Copy after login

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;
  }
}
Copy after login

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

}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!