?作者簡介:大家好,我是Leo,熱愛Java后端開發者,一個想要與大家共同進步的男人😉😉
🍎個人主頁:Leo的博客
💞當前專欄: Java從入門到精通
?特色專欄: MySQL學習
🥭本文內容:SpringSecurity6 | 登錄成功后的JSON處理
📚個人知識庫 :知識庫,歡迎大家訪問
學習參考 :
- 講師:孫帥老師
- 課程:孫哥說SpringSecurity6
1.前言
大家好,我是Leo哥🫣🫣🫣,接到上一節,我們學習通過SpringSecurity登錄成功之后的一些頁面的跳轉。這篇文章我們主要來介紹一下我們通過自定義登錄界面之后的一些細節處理。好了,話不多說讓我們開始吧😎😎😎。
2.概述
在我們現在流行的前后端分離開發中,其實后端已經不需要再進行頁面的跳轉,前后端數據的交換都是通過JSON來進行流傳的。
就比如,我們后端登錄之后,只需要給前端返回一段JSON數據,告訴前端登錄成功即可,具體怎么做呢,我們接著向下看。
3.JSON處理
3.1 自定義Handle
首先我們需要自定義AuthenticationSuccessHandle
并實現他的一些方法。
package org.javatop.custom.config;import cn.hutool.core.lang.hash.Hash;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import java.io.IOException;
import java.util.HashMap;/*** @author : Leo* @version 1.0* @date 2023-12-10 22:03* @description : 響應成功之后的JSON*/
public class MyAuthenticationSuccessHandle implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {HashMap<String, Object> result = new HashMap<>();result.put("msg", "登錄成功");result.put("code", 200);response.setContentType("application/json;charset=utf-8");new ObjectMapper().writeValue(response.getWriter(), result);}
}
3.2 進行配置
在我們的 **MvcCconfig **中進行handler配置。
.successHandler(new MyAuthenticationSuccessHandle()) // 成功之后的JSON處理
然后重啟項目,進行測試。
這個就是我們剛響應的JSON數據。
4.總結
以上便是本文的全部內容,本人才疏學淺,文章有什么錯誤的地方,歡迎大佬們批評指正!我是Leo,一個在互聯網行業的小白,立志成為更好的自己。
如果你想了解更多關于Leo,可以關注公眾號-程序員Leo,后面文章會首先同步至公眾號。