您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)springboot如何使用攔截器判斷是否登錄,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
自定義攔截器實(shí)現(xiàn)HandlerInterceptor接口
創(chuàng)建一個(gè)配置類繼承WebMvcConfigurerAdapter類并重寫addInterceptors方法
代碼:
@Component public class AdminLoginInterceptor implements HandlerInterceptor { // 在請(qǐng)求處理之前調(diào)用,只有返回true才會(huì)執(zhí)行請(qǐng)求 @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // 得到session HttpSession session = httpServletRequest.getSession(true); // 得到對(duì)象 Object admin = session.getAttribute("admin"); // 判斷對(duì)象是否存在 if(admin!=null){ return true; }else{ // 不存在則跳轉(zhuǎn)到登錄頁 httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/adminLogin"); return false; } } // 試圖渲染之后執(zhí)行 @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } // 在請(qǐng)求處理之后,視圖渲染之前執(zhí)行 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
@SpringBootConfiguration public class AdminLoginAdapter extends WebMvcConfigurerAdapter { @Autowired AdminLoginInterceptor adminLoginInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/login/**"); super.addInterceptors(registry); } }
package com.example.demo.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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; /** * 〈一句話功能簡(jiǎn)述〉<br> * 〈攔截器〉 * * @author 丶Zh2Guo * @create 2018/11/22 * @since 1.0.0 */ public class LoginInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class); // 在請(qǐng)求處理之前,只有返回true才會(huì)執(zhí)行請(qǐng)求 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("[攔截器]啟動(dòng)登錄狀態(tài)攔截"); // 得到session HttpSession session = request.getSession(); logger.info("[攔截器]sessionID:" + session.getId()); // 得到用戶信息 Object userInfo = session.getAttribute("userInfo"); //判斷用戶是否登錄 if (userInfo != null) { logger.info("[攔截器]用戶已經(jīng)登錄,用戶名,密碼:" + session.getAttribute("userInfo")); return true; } else { //不存在跳轉(zhuǎn)至登錄頁 response.sendRedirect(request.getContextPath() + "/"); // 跳轉(zhuǎn)到首頁登錄 logger.info("[攔截器]用戶沒有登錄,已跳轉(zhuǎn)到:" + request.getContextPath() + "/"); return false; } } // 視圖渲染后執(zhí)行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } // 請(qǐng)求處理后,視圖渲染前 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
覆蓋其addInterceptors接口,注冊(cè)自定義的攔截器
@Configuration 注解一定要有
package com.example.demo.interceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 〈一句話功能簡(jiǎn)述〉<br> * 〈自定義配置類〉 * * @author 丶Zh2Guo * @create 2018/11/22 * @since 1.0.0 */ @Configuration public class LoginConfig implements WebMvcConfigurer { /** * 該方法用于注冊(cè)攔截器 * 可注冊(cè)多個(gè)攔截器,多個(gè)攔截器組成一個(gè)攔截器鏈 */ @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns 添加路徑 // excludePathPatterns 排除路徑 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/sys/*"); // 攔截sys路徑下的url // .excludePathPatterns(""); } }
/** * Copyright (C), 2017-2018, XXX有限公司 * FileName: LoginController * Author: 丶Zh2Guo * Date: 2018/11/22 11:10 * Description: 登錄 * History: * <author> <time> <version> <desc> * 作者姓名 修改時(shí)間 版本號(hào) 描述 */ package com.example.demo.controller; import com.example.demo.dao.UserDAO; import com.example.demo.pojo.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; /** * 〈一句話功能簡(jiǎn)述〉<br> * 〈登錄〉 * * @author 丶Zh2Guo * @create 2018/11/22 * @since 1.0.0 */ @Controller public class LoginController { // 日志 private Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private UserDAO userDAO; // 啟動(dòng)服務(wù)自動(dòng)跳轉(zhuǎn)登錄 // @RequestMapping(value = {"/", "/login"}) @RequestMapping(value = "/") public String login() { return "login"; } // 登錄 @RequestMapping(value = "/loginCheck", method = RequestMethod.POST) @ResponseBody public String loginCheck(HttpServletRequest request) { // 獲取登錄信息 String userName = request.getParameter("userName"); String password = request.getParameter("password"); // 封裝成對(duì)象 User user = new User(); user.setUserName(userName); user.setPassword(password); // 校驗(yàn)用戶信息 User info = userDAO.checkUser(user); if (info != null) { request.getSession().setAttribute("userInfo", userName + "-" + password); logger.info("登錄成功,用戶名:" + userName + "密碼:" + password); return "success"; } else { logger.info("登錄失敗,用戶名:" + userName + "密碼:" + password); return "fail"; } } }
上述就是小編為大家分享的springboot如何使用攔截器判斷是否登錄了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。