SpringBoot登錄攔截配置詳解(實測可用)
背景:寫一個用戶登錄攔截,在網(wǎng)上找了一圈沒找到好用的,于是自己試驗了一下,總結(jié)出來,分享給大家。
1.自定義登錄攔截器LoginInterceptor
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 這里是關(guān)鍵 User loginUser = (User) request.getSession().getAttribute('user'); if (loginUser == null) { // 未登錄拋出異常,交給統(tǒng)一異常處理器處理 throw new CustomException(ResultCode.USER_NOT_LOGIN); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }}
2.在WebConfigurer中添加攔截器
@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //注冊TestInterceptor攔截器 registry.addInterceptor(new LoginInterceptor()).addPathPatterns('/**')// 排除登錄注冊等接口,注意這里的格式是 /**/xxx.excludePathPatterns('/**/login', '/**/register'); }}
3.登錄接口
/** * 登錄 * @return 用戶信息 */public User login(UserVO userVO. HttpServlet) { String username = userVO.getUsername(); String password = userVO.getPassword(); User user = userMapper.findByUsernameAndPassword(username, password); // 未找到用戶 if(user == null) { throw new CustomException(ResultCode.USER_ACCOUNT_ERROR); } // 設(shè)置session中的用戶信息 SessionUtils.setSessionAttribute('user', user); return user;}
文中的代碼細節(jié)不一一列舉了,這里重點討論的攔截器,感興趣的朋友可以私聊我獲取其他代碼。
結(jié)果
未登錄的情況下,請求普通接口提示未登錄。
請求登錄接口。
登錄后再去請求普通接口,返回正常。
-END-
到此這篇關(guān)于SpringBoot登錄攔截配置詳解(實測可用)的文章就介紹到這了,更多相關(guān)SpringBoot登錄攔截內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. IntelliJ IDEA導(dǎo)入jar包的方法2. SSM框架JSP使用Layui實現(xiàn)layer彈出層效果3. 刪除docker里建立容器的操作方法4. IntelliJ IDEA導(dǎo)出項目的方法5. .Net中的Http請求調(diào)用詳解(Post與Get)6. 如果你恨一個程序員,忽悠他去做iOS開發(fā)7. JS如何在數(shù)組指定位置插入元素8. IDEA調(diào)試源碼小技巧之辨別抽象類或接口多種實現(xiàn)類的正確路徑9. java使用xfire搭建webservice服務(wù)的過程詳解10. Java源碼解析之ClassLoader
