Spring Boot 實現(xiàn)登錄攔截器
對于管理系統(tǒng)或其他需要用戶登錄的系統(tǒng),登錄驗證都是必不可少的環(huán)節(jié),在SpringBoot開發(fā)的項目中,通過實現(xiàn)攔截器來實現(xiàn)用戶登錄攔截并驗證。
1、Spring Boot實現(xiàn)登錄攔截原理
SpringBoot通過實現(xiàn)HandlerInterceptor接口實現(xiàn)攔截器,通過實現(xiàn)WebMvcConfigurer接口實現(xiàn)一個配置類,在配置類中注入攔截器,最后再通過@Configuration注解注入配置。
1.1、實現(xiàn)HandlerInterceptor接口
實現(xiàn)HandlerInterceptor接口需要實現(xiàn)3個方法:preHandle、postHandle、afterCompletion.
3個方法各自的功能如下:
public?class?UserLoginInterceptor?implements?HandlerInterceptor?{
????/***
?????* 在請求處理之前進行調(diào)用(Controller方法調(diào)用之前)
?????*/
????@Override
????public?boolean?preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)?throws?Exception {
????????System.out.println("執(zhí)行了攔截器的preHandle方法");
????????try?{
????????????HttpSession session = request.getSession();
????????????//統(tǒng)一攔截(查詢當前session是否存在user)(這里user會在每次登錄成功后,寫入session)
????????????User user = (User) session.getAttribute("user");
????????????if?(user != null) {
????????????????return?true;
????????????}
????????????response.sendRedirect(request.getContextPath() + "login");
????????} catch?(Exception e) {
????????????e.printStackTrace();
????????}
????????return?false;
????????//如果設置為false時,被請求時,攔截器執(zhí)行到此處將不會繼續(xù)操作
????????//如果設置為true時,請求將會繼續(xù)執(zhí)行后面的操作
????}
????/***
?????* 請求處理之后進行調(diào)用,但是在視圖被渲染之前(Controller方法調(diào)用之后)
?????*/
????@Override
????public?void?postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)?throws?Exception {
????????System.out.println("執(zhí)行了攔截器的postHandle方法");
????}
????/***
?????* 整個請求結(jié)束之后被調(diào)用,也就是在DispatchServlet渲染了對應的視圖之后執(zhí)行(主要用于進行資源清理工作)
?????*/
????@Override
????public?void?afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)?throws?Exception {
????????System.out.println("執(zhí)行了攔截器的afterCompletion方法");
????}
}preHandle在Controller之前執(zhí)行,因此攔截器的功能主要就是在這個部分實現(xiàn):
檢查session中是否有user對象存在; 如果存在,就返回true,那么Controller就會繼續(xù)后面的操作; 如果不存在,就會重定向到登錄界面。就是通過這個攔截器,使得Controller在執(zhí)行之前,都執(zhí)行一遍preHandle.
1.2、實現(xiàn)WebMvcConfigurer接口,注冊攔截器
@Configuration
public?class?LoginConfig?implements?WebMvcConfigurer?{
????@Override
????public?void?addInterceptors(InterceptorRegistry registry)?{
????????//注冊TestInterceptor攔截器
????????InterceptorRegistration registration = registry.addInterceptor(new?UserLoginInterceptor());
????????registration.addPathPatterns("/**"); //所有路徑都被攔截
????????registration.excludePathPatterns( //添加不攔截路徑
????????????????"/login", //登錄路徑
????????????????"/**/*.html", //html靜態(tài)資源
????????????????"/**/*.js", //js靜態(tài)資源
????????????????"/**/*.css"??????????????????//css靜態(tài)資源
????????);
????}
}1.3、保持登錄狀態(tài)
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET)
public?String?index(Model model, HttpServletRequest request) {
????User user = (User) request.getSession().getAttribute("user");
????model.addAttribute("user", user);
????return?"users/index";
}
@RequestMapping(value = {"/login"}, method = RequestMethod.GET)
public?String?loginIndex() {
????return?"users/login";
}
@RequestMapping(value = {"/login"}, method = RequestMethod.POST)
public?String?login(@RequestParam(name = "username")String?username, @RequestParam(name = "password")String?password,
????????????????????Model model, HttpServletRequest request) {
????User user = userService.getPwdByUsername(username);
????String?pwd = user.getPassword();
????String?password1 = MD5Utils.md5Code(password).toUpperCase();
????String?password2 = MD5Utils.md5Code(password1).toUpperCase();
????if?(pwd.equals(password2)) {
????????model.addAttribute("user", user);
????????request.getSession().setAttribute("user", user);
????????return?"redirect:/index";
????} else?{
????????return?"users/failed";
????}
}2、代碼實現(xiàn)及示例

3、效果驗證
3.1、訪問localhost:8081/index頁面:

被重定向到了localhost:8081/login,實現(xiàn)了登錄攔截。
3.2、正確輸入用戶名和密碼登錄

3.3、再次訪問localhost:8081/index

PS:如果覺得我的分享不錯,歡迎大家隨手點贊、在看。
(完) 加我"微信"?獲取一份 最新Java面試題資料 請備注:666,不然不通過~
最近好文
最近面試BAT,整理一份面試資料《Java面試BAT通關手冊》,覆蓋了Java核心技術、JVM、Java并發(fā)、SSM、微服務、數(shù)據(jù)庫、數(shù)據(jù)結(jié)構等等。 獲取方式:關注公眾號并回復?java?領取,更多內(nèi)容陸續(xù)奉上。 明天見(??ω??)??
評論
圖片
表情
