springboot使用攔截器判斷是否登錄
更新時(shí)間:2021年11月09日 16:41:19 作者:92.4
這篇文章主要介紹了springboot使用攔截器判斷是否登錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
springboot攔截器判斷是否登錄
實(shí)現(xiàn)攔截器的兩個(gè)步驟
- 自定義攔截器實(shí)現(xiàn)HandlerInterceptor接口
- 創(chuàng)建一個(gè)配置類繼承WebMvcConfigurerAdapter類并重寫addInterceptors方法
代碼:
1、自定義攔截器
@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)到登錄頁(yè)
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 {
}
}
2、自定義配置類繼承WebMvcConfigurerAdapter
@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);
}
}
springboot 增加攔截器判斷是否登錄
1、創(chuàng)建攔截器
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 丶Zh1Guo
* @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)至登錄頁(yè)
response.sendRedirect(request.getContextPath() + "/"); // 跳轉(zhuǎn)到首頁(yè)登錄
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 {
}
}
2、繼承WebMvcConfigureAdapter類
覆蓋其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 丶Zh1Guo
* @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("");
}
}
3、LoginController
/**
* Copyright (C), 2017-2018, XXX有限公司
* FileName: LoginController
* Author: 丶Zh1Guo
* 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 丶Zh1Guo
* @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";
}
}
}
4、未登錄會(huì)自動(dòng)跳轉(zhuǎn)到登錄頁(yè)面



以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java并發(fā)學(xué)習(xí)之Executor源碼解析
這篇文章主要為大家介紹了java并發(fā)學(xué)習(xí)之Executor源碼示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
java求最大公約數(shù)與最小公倍數(shù)的方法示例
這篇文章主要介紹了java求最大公約數(shù)與最小公倍數(shù)的方法,涉及java數(shù)值運(yùn)算的相關(guān)操作技巧,并附帶分析了eclipse環(huán)境下設(shè)置運(yùn)行輸入?yún)?shù)的相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
Java對(duì)象和Map之間相互轉(zhuǎn)換的五種方法
在Java開發(fā)中,經(jīng)常需要將Java對(duì)象轉(zhuǎn)換成Map,或者反過來將Map轉(zhuǎn)換成Java對(duì)象,這種轉(zhuǎn)換在很多場(chǎng)景下都非常有用,比如在序列化和反序列化過程中、在數(shù)據(jù)傳輸和持久化時(shí)、或者在進(jìn)行對(duì)象屬性的批量操作時(shí),本文將介紹幾種不同的方法來實(shí)現(xiàn)Java對(duì)象和Map之間的相互轉(zhuǎn)換2025-02-02
使用Lucene實(shí)現(xiàn)一個(gè)簡(jiǎn)單的布爾搜索功能
Lucene是一個(gè)全文搜索框架,而不是應(yīng)用產(chǎn)品。因此它并不像www.baidu.com 或者google Desktop那么拿來就能用,它只是提供了一種工具讓你能實(shí)現(xiàn)這些產(chǎn)品。接下來通過本文給大家介紹使用Lucene實(shí)現(xiàn)一個(gè)簡(jiǎn)單的布爾搜索功能2017-04-04
SpringBoot使用Maven實(shí)現(xiàn)多環(huán)境配置管理
軟件開發(fā)中經(jīng)常有開發(fā)環(huán)境、測(cè)試環(huán)境、生產(chǎn)環(huán)境,而且一般這些環(huán)境配置會(huì)各不相同,本文主要介紹了SpringBoot使用Maven實(shí)現(xiàn)多環(huán)境配置管理,感興趣的可以了解一下2024-01-01
idea maven pom不自動(dòng)更新的解決方法
這篇文章主要介紹了idea maven pom不自動(dòng)更新的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08

