> Java > java지도 시간 > 본문

JavaWeb은 세션과 쿠키를 사용하여 로그인 인증 코드 예제 공유를 구현합니다.

黄舟
풀어 주다: 2017-03-18 10:17:32
원래의
1461명이 탐색했습니다.

이 글에서는 SessionCookie를 활용하여 로그인 인증을 구현하는 JavaWeb을 주로 소개하고 있으니 관심 있는 분들은 참고하시기 바랍니다.

백그라운드 관리 페이지는 로그인이 필요한 경우가 많습니다. 이 경우 로그인상태

기록을 위해 Session이 필요합니다. 구현도 매우 간단합니다. , 그냥 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
@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을 다음으로 변경하면 됩니다. 쿠키

일반적인 상황에서는 쿠키를 사용합니다

쿠키와 세션 방법은 유사합니다

쿠키의 사용자 정의 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
@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";
  }

}
로그인 후 복사

스프링 구성은 이전과 똑같습니다

참고

이것은 단지 예시일 뿐이므로 실제 프로젝트에서는 Cookie의 키와 값을 특수하게 처리하는 것이 좋습니다. 그렇지 않으면 보안 문제가 발생할 수 있습니다

위 내용은 JavaWeb은 세션과 쿠키를 사용하여 로그인 인증 코드 예제 공유를 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!