SpringBoot29 登錄邏輯、登錄狀態判斷


 

1 知識點掃盲

  瀏覽器和服務器之間時通過session來確定連接狀態的,瀏覽器第一次請求時服務端會自動生成一個session,並將這個sessionId傳回給瀏覽器,瀏覽器將這個sessionId存放在cookie中,下一次瀏覽器訪問服務器時就會將這個sessionId以cookie的形式傳遞到服務器,服務器接送到這個sessionId后就可以判斷發送這個請求的瀏覽器之前是否訪問過。

  在進行登錄認證邏輯時,通常會在登錄認證成功后將用戶信息保存到session中;整個系統會對出登錄和登出操作之外的請求進行攔截,在攔截器中會判斷session中是否有用戶的數據,如果有就跳轉到controller層執行對應的請求,如果沒有就直接返回一個提示信息。(PS: 每個客戶端第一次訪問服務器時服務端都會自動創建一個session)

2 基於SpringBoot的登錄狀態判斷

  2.1 整體流程圖

  2.2 代碼實現

    2.2.1 創建一個SpringBoot

      利用IDEA創建一個SpringBoot項目,只引入web模塊

    2.2.2 創建一個攔截器

      攔截出登錄請求以外的所有請求,通過判斷session是否有用戶信息來判斷登錄狀態

package com.xunyji.springboot_login_session.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 王楊帥
 * @create 2018-09-11 21:31
 * @desc 登錄狀態攔截器
 **/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("==========登錄狀態攔截");

        HttpSession session = request.getSession();
        log.info("sessionId為:" + session.getId());

        // 獲取用戶信息,如果沒有用戶信息直接返回提示信息
        Object userInfo = session.getAttribute("userInfo");
        if (userInfo == null) {
            log.info("沒有登錄");
            response.getWriter().write("Please Login In");
            return false;
        } else {
            log.info("已經登錄過啦,用戶信息為:" + session.getAttribute("userInfo"));
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
LoginInterceptor.java

    2.2.3 添加攔截器

package com.xunyji.springboot_login_session.config;

import com.xunyji.springboot_login_session.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author 王楊帥
 * @create 2018-09-11 21:35
 * @desc
 **/
@Configuration
public class LoginConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/test/login");
    }
}
LoginConfig.java

    2,2.4 測試控制層

package com.xunyji.springboot_login_session.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 王楊帥
 * @create 2018-09-11 21:17
 * @desc
 **/
@RestController
@RequestMapping(value = "/test")
@Slf4j
public class TestController {

    @GetMapping(value = "/test01")
    public String test01() {
        String info = "測試01";
        log.info(info);
        return info;
    }

    @GetMapping(value = "/test02")
    public String test02() {
        String info = "test02";
        log.info(info);
        return info;
    }

    /**
     * 登錄邏輯
     * @param name 用戶名
     * @param pwd 用戶密碼
     * @param request
     * @return
     */
    @GetMapping(value = "/login")
    public String login(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "pwd") String pwd,
            HttpServletRequest request
    ) {
        String info = "登錄邏輯";
        log.info(info);

        // 登錄認證,認證成功后將用戶信息放到session中
        if (name.equals("fury") && pwd.equals("111111")) {
            request.getSession().setAttribute("userInfo", name + " - " + pwd);
            info = "登錄成功";
        } else {
            info = "登錄失敗";
        }

        log.info(info);
        return info;
    }

    /**
     * 登出操作
     * @param request
     * @return
     */
    @GetMapping(value = "/loginout")
    public String loginout(HttpServletRequest request) {
        String info = "登出操作";
        log.info(info);
        HttpSession session = request.getSession();

        // 將用戶信息從session中刪除
        session.removeAttribute("userInfo");

        Object userInfo = session.getAttribute("userInfo");
        if (userInfo == null) {
            info = "登出成功";
        } else {
            info = "登出失敗";
        }
        log.info(info);

        return info;

    }

}
TestController.java

 

3 代碼匯總

  點擊獲取

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM