Springboot中登錄后關(guān)于cookie和session攔截問題的案例分析
一、前言
1、簡單的登錄驗(yàn)證可以通過Session或者Cookie實(shí)現(xiàn)。
2、每次登錄的時(shí)候都要進(jìn)數(shù)據(jù)庫校驗(yàn)下賬戶名和密碼,只是加了cookie 或session驗(yàn)證后;比如登錄頁面A,登錄成功后進(jìn)入頁面B,若此時(shí)cookie過期,在頁面B中新的請求url到頁面c,系統(tǒng)會讓它回到初始的登錄頁面。(類似單點(diǎn)登錄sso(single sign on))。
3、另外,無論基于Session還是Cookie的登錄驗(yàn)證,都需要對HandlerInteceptor進(jìn)行配置,增加對URL的攔截過濾機(jī)制。
二、利用Cookie進(jìn)行登錄驗(yàn)證
1、配置攔截器代碼如下:
public class CookiendSessionInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.debug("進(jìn)入攔截器");
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0){
for(Cookie cookie:cookies) {
log.debug("cookie===for遍歷"+cookie.getName());
if (StringUtils.equalsIgnoreCase(cookie.getName(), "isLogin")) {
log.debug("有cookie ---isLogin,并且cookie還沒過期...");
//遍歷cookie如果找到登錄狀態(tài)則返回true繼續(xù)執(zhí)行原來請求url到controller中的方法
return true;
}
}
}
log.debug("沒有cookie-----cookie時(shí)間可能到期,重定向到登錄頁面后請重新登錄。。。");
response.sendRedirect("index.html");
//返回false,不執(zhí)行原來controller的方法
return false; }
@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、在Springboot中攔截的請求不管是配置監(jiān)聽器(定義一個(gè)類實(shí)現(xiàn)一個(gè)接口HttpSessionListener )、過濾器、攔截器,都要配置如下此類實(shí)現(xiàn)一個(gè)接口中的兩個(gè)方法。
代碼如下:
@Configuration
public class WebConfig implements WebMvcConfigurer {
// 這個(gè)方法是用來配置靜態(tài)資源的,比如html,js,css,等等
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}
// 這個(gè)方法用來注冊攔截器,我們自己寫好的攔截器需要通過這里添加注冊才能生效
@Override
public void addInterceptors(InterceptorRegistry registry) {
//addPathPatterns("/**") 表示攔截所有的請求
//excludePathPatterns("/firstLogin","/zhuce");設(shè)置白名單,就是攔截器不攔截。首次輸入賬號密碼登錄和注冊不用攔截!
//登錄頁面在攔截器配置中配置的是排除路徑,可以看到即使放行了,還是會進(jìn)入prehandle,但是不會執(zhí)行任何操作。
registry.addInterceptor(new CookiendSessionInterceptor()).addPathPatterns("/**").excludePathPatterns("/",
"/**/login",
"/**/*.html",
"/**/*.js",
"/**/*.css",
"/**/*.jpg");
}
}
3.前臺登錄頁面index.html(我把這個(gè)html放在靜態(tài)資源了,也讓攔截器放行了此路由url)
前端測試就是一個(gè)簡單的form表單提交
<!--測試cookie和sessionid--> <form action="/login" method="post"> 賬號:<input type="text" name="name1" placeholder="請輸入賬號"><br> 密碼:<input type="password" name="pass1" placeholder="請輸入密碼"><br> <input type="submit" value="登錄"> </form>
4、后臺控制層Controller業(yè)務(wù)邏輯:登錄頁面index.html,登錄成功后 loginSuccess.html。
在loginSuccess.html中可提交表單進(jìn)入次頁demo.html,也可點(diǎn)擊“退出登錄”后臺清除沒有超時(shí)的cookie,并且回到初始登錄頁面。
@Controller
@Slf4j
@RequestMapping(value = "/")
public class TestCookieAndSessionController {
@Autowired JdbcTemplate jdbcTemplate;
/** * 首次登錄,輸入賬號和密碼,數(shù)據(jù)庫驗(yàn)證無誤后,響應(yīng)返回你設(shè)置的cookie。再次輸入賬號密碼登錄或者首次登錄后再請求下一個(gè)頁面,就會在請求頭中攜帶cookie, * 前提是cookie沒有過期。 * 此url請求方法不管是首次登錄還是第n次登錄,攔截器都不會攔截。 * 但是每次(首次或者第N次)登錄都要進(jìn)行,數(shù)據(jù)庫查詢驗(yàn)證賬號和密碼。 * 做這個(gè)目的是如果登錄頁面A,登錄成功后進(jìn)頁面B,頁面B有鏈接進(jìn)頁面C,如果cookie超時(shí),重新回到登錄頁面A。(類似單點(diǎn)登錄) */
@PostMapping(value = "login")
public String test(HttpServletRequest request, HttpServletResponse response, @RequestParam("name1")String name,@RequestParam("pass1")String pass) throws Exception{
try {
Map<String, Object> result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass});
if(result==null || result.size()==0){
log.debug("賬號或者密碼不正確或者此人賬號沒有注冊");
throw new Exception("賬號或者密碼不正確或者此人賬號沒有注冊!");
}else{
log.debug("查詢滿足條數(shù)----"+result);
Cookie cookie = new Cookie("isLogin", "success");
cookie.setMaxAge(30);
cookie.setPath("/");
response.addCookie(cookie);
request.setAttribute("isLogin", name);
log.debug("首次登錄,查詢數(shù)據(jù)庫用戶名和密碼無誤,登錄成功,設(shè)置cookie成功");
return "loginSuccess"; }
} catch (DataAccessException e) {
e.printStackTrace();
return "error1";
}
}
/**測試登錄成功后頁面loginSuccess ,進(jìn)入次頁demo.html*/
@PostMapping(value = "sub")
public String test() throws Exception{
return "demo";
}
/** 能進(jìn)到此方法中,cookie一定沒有過期。因?yàn)閿r截器在前面已經(jīng)判斷力。過期,攔截器重定向到登錄頁面。過期退出登錄,清空cookie。*/
@RequestMapping(value = "exit",method = RequestMethod.POST)
public String exit(HttpServletRequest request,HttpServletResponse response) throws Exception{
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
if("isLogin".equalsIgnoreCase(cookie.getName())){
log.debug("退出登錄時(shí),cookie還沒過期,清空cookie");
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setPath("/");
response.addCookie(cookie);
break;
}
}
//重定向到登錄頁面
return "redirect:index.html";
}
}
5、效果演示:
①在登錄“l(fā)ocalhost:8082”輸入賬號登錄頁面登錄:

②攔截器我設(shè)置了放行/login,所以請求直接進(jìn)Controller相應(yīng)的方法中:
日志信息如下:

下圖可以看出,瀏覽器有些自帶的不止一個(gè)cookie,這里不要管它們。

③在loginSuccess.html,進(jìn)入次頁demo.html。cookie沒有過期順利進(jìn)入demo.html,并且/sub方法經(jīng)過攔截器(此請求請求頭中攜帶cookie)。
過期的話直接回到登錄頁面(這里不展示了)

④在loginSuccess.html點(diǎn)擊“退出登錄”,后臺清除我設(shè)置的沒過期的cookie=isLogin,回到登錄頁面。
三、利用Session進(jìn)行登錄驗(yàn)證
1、修改攔截器配置略微修改下:

Interceptor也略微修改下:還是上面的preHandle方法中:

2.核心
前端我就不展示了,就是一個(gè)form表單action="login1"
后臺代碼如下:
/**利用session進(jìn)行登錄驗(yàn)證*/
@RequestMapping(value = "login1",method = RequestMethod.POST)
public String testSession(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("name1")String name,
@RequestParam("pass1")String pass) throws Exception{
try {
Map<String, Object> result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass});
if(result!=null && result.size()>0){
String requestURI = request.getRequestURI();
log.debug("此次請求的url:{}",requestURI);
HttpSession session = request.getSession();
log.debug("session="+session+"session.getId()="+session.getId()+"session.getMaxInactiveInterval()="+session.getMaxInactiveInterval());
session.setAttribute("isLogin1", "true1");
}
} catch (DataAccessException e) {
e.printStackTrace();
return "error1";
}
return "loginSuccess";
}
//登出,移除登錄狀態(tài)并重定向的登錄頁
@RequestMapping(value = "/exit1", method = RequestMethod.POST)
public String loginOut(HttpServletRequest request) {
request.getSession().removeAttribute("isLogin1");
log.debug("進(jìn)入exit1方法,移除isLogin1");
return "redirect:index.html";
}
}
日志如下:可以看見springboot內(nèi)置的tomcat中sessionid就是請求頭中的jsessionid,而且默認(rèn)時(shí)間1800秒(30分鐘)。
我也不清楚什么進(jìn)入攔截器2次,因?yàn)槲襩ogin1設(shè)置放行了,肯定不會進(jìn)入攔截器??赡苁鞘裁挫o態(tài)別的什么資源吧。

session.getId()=F88CF6850CD575DFB3560C3AA7BEC89F==下圖的JSESSIONID

//點(diǎn)擊退出登錄,請求退出url的請求頭還是攜帶JSESSIONID,除非瀏覽器關(guān)掉才消失。(該session設(shè)置的屬性isLogin1移除了,session在不關(guān)瀏覽器情況下或者超過默認(rèn)時(shí)間30分鐘后,session才會自動清除?。?/p>


四、完結(jié)
到此這篇關(guān)于Springboot中登錄后關(guān)于cookie和session攔截案例的文章就介紹到這了,更多相關(guān)Springboot登錄關(guān)于cookie和session攔截內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中通過實(shí)現(xiàn)WebMvcConfigurer參數(shù)校驗(yàn)的方法示例
這篇文章主要介紹了SpringBoot中通過實(shí)現(xiàn)WebMvcConfigurer參數(shù)校驗(yàn)的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
SpringBoot中手動開啟數(shù)據(jù)庫事務(wù)的四種方式
這篇文章給大家介紹SpringBoot中手動開啟數(shù)據(jù)庫事務(wù)的四種方式,每種方式結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2025-12-12
Java實(shí)現(xiàn)List與數(shù)組互相轉(zhuǎn)換的兩種方法
在 Java 編程中,List 和數(shù)組是兩種常用的數(shù)據(jù)結(jié)構(gòu),List 提供了動態(tài)大小、豐富的操作方法,而數(shù)組則以其高效的隨機(jī)訪問和內(nèi)存效率著稱,在實(shí)際開發(fā)中,我們經(jīng)常需要在這兩者之間進(jìn)行轉(zhuǎn)換,本文將深入探討 List 與數(shù)組之間的相互轉(zhuǎn)換,需要的朋友可以參考下2025-12-12

