SpringBoot中實(shí)現(xiàn)登錄攔截器的代碼實(shí)例
1、SpringBoot實(shí)現(xiàn)登錄攔截的原理
SpringBoot通過實(shí)現(xiàn)HandlerInterceptor接口實(shí)現(xiàn)攔截器,通過實(shí)現(xiàn)WebMvcConfigurer接口實(shí)現(xiàn)一個(gè)配置類,在配置類中注入攔截器,最后再通過@Configuration注解注入配置.
1.1、實(shí)現(xiàn)HandlerInterceptor接口
實(shí)現(xiàn)HandlerInterceptor接口需要實(shí)現(xiàn)3個(gè)方法:preHandle、postHandle、afterCompletion.
3個(gè)方法各自的功能如下:
package blog.interceptor; import blog.entity.User; 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; public class UserLoginInterceptor implements HandlerInterceptor { /*** * 在請(qǐng)求處理之前進(jìn)行調(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)一攔截(查詢當(dāng)前session是否存在user)(這里user會(huì)在每次登錄成功后,寫入session) User user = (User) session.getAttribute("user"); if (user != null) { return true; } response.sendRedirect(request.getContextPath() + "login"); } catch (Exception e) { e.printStackTrace(); } return false; //如果設(shè)置為false時(shí),被請(qǐng)求時(shí),攔截器執(zhí)行到此處將不會(huì)繼續(xù)操作 //如果設(shè)置為true時(shí),請(qǐng)求將會(huì)繼續(xù)執(zhí)行后面的操作 } /*** * 請(qǐng)求處理之后進(jìn)行調(diào)用,但是在視圖被渲染之前(Controller方法調(diào)用之后) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("執(zhí)行了攔截器的postHandle方法"); } /*** * 整個(gè)請(qǐng)求結(jié)束之后被調(diào)用,也就是在DispatchServlet渲染了對(duì)應(yīng)的視圖之后執(zhí)行(主要用于進(jìn)行資源清理工作) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("執(zhí)行了攔截器的afterCompletion方法"); } }
preHandle在Controller之前執(zhí)行,因此攔截器的功能主要就是在這個(gè)部分實(shí)現(xiàn):
- 檢查session中是否有user對(duì)象存在;
- 如果存在,就返回true,那么Controller就會(huì)繼續(xù)后面的操作;
- 如果不存在,就會(huì)重定向到登錄界面
就是通過這個(gè)攔截器,使得Controller在執(zhí)行之前,都執(zhí)行一遍preHandle
1.2、實(shí)現(xiàn)WebMvcConfigurer接口,注冊(cè)攔截器
實(shí)現(xiàn)WebMvcConfigurer接口來實(shí)現(xiàn)一個(gè)配置類,將上面實(shí)現(xiàn)的攔截器的一個(gè)對(duì)象注冊(cè)到這個(gè)配置類中.
package blog.config; import blog.interceptor.UserLoginInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class LoginConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //注冊(cè)TestInterceptor攔截器 InterceptorRegistration registration = registry.addInterceptor(new UserLoginInterceptor()); registration.addPathPatterns("/**"); //所有路徑都被攔截 registration.excludePathPatterns( //添加不攔截路徑 "/login", //登錄路徑 "/**/*.html", //html靜態(tài)資源 "/**/*.js", //js靜態(tài)資源 "/**/*.css" //css靜態(tài)資源 ); } }
將攔截器注冊(cè)到了攔截器列表中,并且指明了攔截哪些訪問路徑,不攔截哪些訪問路徑,不攔截哪些資源文件;最后再以@Configuration注解將配置注入。
1.3、保持登錄狀態(tài)
只需一次登錄,如果登錄過,下一次再訪問的時(shí)候就無(wú)需再次進(jìn)行登錄攔截,可以直接訪問網(wǎng)站里面的內(nèi)容了。
在正確登錄之后,就將user保存到session中,再次訪問頁(yè)面的時(shí)候,登錄攔截器就可以找到這個(gè)user對(duì)象,就不需要再次攔截到登錄界面了.
@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、代碼實(shí)現(xiàn)及示例
代碼實(shí)現(xiàn)如上所示。
在登錄成功之后,將user信息保存到session中,下一次登錄時(shí)瀏覽器根據(jù)自己的SESSIONID就可以找到對(duì)應(yīng)的session,就不要再次登錄了,可以從Chrome瀏覽器中看到。
3、效果驗(yàn)證
3.1、訪問localhost:8081/index頁(yè)面:
被重定向到了localhost:8081/login,實(shí)現(xiàn)了登錄攔截。
3.2、正確輸入用戶名和密碼登錄
3.3、再次訪問localhost:8081/index
沒有再次被登錄攔截器攔截,證明可以保持登錄.
到此這篇關(guān)于SpringBoot中實(shí)現(xiàn)登錄攔截器的代碼實(shí)例的文章就介紹到這了,更多相關(guān)SpringBoot實(shí)現(xiàn)登錄攔截器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot 創(chuàng)建容器的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot 創(chuàng)建容器的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Mybatis-plus配置多數(shù)據(jù)源,連接多數(shù)據(jù)庫(kù)方式
這篇文章主要介紹了Mybatis-plus配置多數(shù)據(jù)源,連接多數(shù)據(jù)庫(kù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06RestTemplate報(bào)錯(cuò)400 Bad Request的解決方案
在使用Spring Boot時(shí),若直接通過@Autowired注入RestTemplate可能會(huì)遇到400BadRequest錯(cuò)誤,原因在于Spring Boot官方文檔指出,由于RestTemplate實(shí)例通常需要在使用前進(jìn)行定制,因此Spring Boot不會(huì)自動(dòng)配置單個(gè)RestTemplate Bean2024-11-11基于JavaBean編輯器讀取peroperties文件的實(shí)例
下面小編就為大家?guī)硪黄贘avaBean編輯器讀取peroperties文件的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10Java 入門圖形用戶界面設(shè)計(jì)之復(fù)選框
圖形界面(簡(jiǎn)稱GUI)是指采用圖形方式顯示的計(jì)算機(jī)操作用戶界面。與早期計(jì)算機(jī)使用的命令行界面相比,圖形界面對(duì)于用戶來說在視覺上更易于接受,本篇精講Java語(yǔ)言中關(guān)于圖形用戶界面的復(fù)選框2022-02-02