Springboot中登錄后關(guān)于cookie和session攔截問題的案例分析
一、前言
1、簡單的登錄驗證可以通過Session或者Cookie實現(xiàn)。2、每次登錄的時候都要進(jìn)數(shù)據(jù)庫校驗下賬戶名和密碼,只是加了cookie 或session驗證后;比如登錄頁面A,登錄成功后進(jìn)入頁面B,若此時cookie過期,在頁面B中新的請求url到頁面c,系統(tǒng)會讓它回到初始的登錄頁面。(類似單點登錄sso(single sign on))。3、另外,無論基于Session還是Cookie的登錄驗證,都需要對HandlerInteceptor進(jìn)行配置,增加對URL的攔截過濾機(jī)制。
二、利用Cookie進(jì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時間可能到期,重定向到登錄頁面后請重新登錄。。。'); 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)聽器(定義一個類實現(xiàn)一個接口HttpSessionListener )、過濾器、攔截器,都要配置如下此類實現(xiàn)一個接口中的兩個方法。代碼如下:
@Configuration public class WebConfig implements WebMvcConfigurer { // 這個方法是用來配置靜態(tài)資源的,比如html,js,css,等等 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { } // 這個方法用來注冊攔截器,我們自己寫好的攔截器需要通過這里添加注冊才能生效 @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(我把這個html放在靜態(tài)資源了,也讓攔截器放行了此路由url)前端測試就是一個簡單的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,也可點擊“退出登錄”后臺清除沒有超時的cookie,并且回到初始登錄頁面。
@Controller @Slf4j @RequestMapping(value = '/') public class TestCookieAndSessionController { @Autowired JdbcTemplate jdbcTemplate; /** * 首次登錄,輸入賬號和密碼,數(shù)據(jù)庫驗證無誤后,響應(yīng)返回你設(shè)置的cookie。再次輸入賬號密碼登錄或者首次登錄后再請求下一個頁面,就會在請求頭中攜帶cookie, * 前提是cookie沒有過期。 * 此url請求方法不管是首次登錄還是第n次登錄,攔截器都不會攔截。 * 但是每次(首次或者第N次)登錄都要進(jìn)行,數(shù)據(jù)庫查詢驗證賬號和密碼。 * 做這個目的是如果登錄頁面A,登錄成功后進(jìn)頁面B,頁面B有鏈接進(jìn)頁面C,如果cookie超時,重新回到登錄頁面A。(類似單點登錄) */ @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一定沒有過期。因為攔截器在前面已經(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('退出登錄時,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)的方法中:日志信息如下:
下圖可以看出,瀏覽器有些自帶的不止一個cookie,這里不要管它們。
③在loginSuccess.html,進(jìn)入次頁demo.html。cookie沒有過期順利進(jìn)入demo.html,并且/sub方法經(jīng)過攔截器(此請求請求頭中攜帶cookie)。過期的話直接回到登錄頁面(這里不展示了)
④在loginSuccess.html點擊“退出登錄”,后臺清除我設(shè)置的沒過期的cookie=isLogin,回到登錄頁面。
三、利用Session進(jìn)行登錄驗證
1、修改攔截器配置略微修改下:
Interceptor也略微修改下:還是上面的preHandle方法中:
2.核心前端我就不展示了,就是一個form表單action='login1'后臺代碼如下:
/**利用session進(jì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)時間1800秒(30分鐘)。我也不清楚什么進(jìn)入攔截器2次,因為我login1設(shè)置放行了,肯定不會進(jìn)入攔截器。可能是什么靜態(tài)別的什么資源吧。
session.getId()=F88CF6850CD575DFB3560C3AA7BEC89F==下圖的JSESSIONID
//點擊退出登錄,請求退出url的請求頭還是攜帶JSESSIONID,除非瀏覽器關(guān)掉才消失。(該session設(shè)置的屬性isLogin1移除了,session在不關(guān)瀏覽器情況下或者超過默認(rèn)時間30分鐘后,session才會自動清除!)
四、完結(jié)
到此這篇關(guān)于Springboot中登錄后關(guān)于cookie和session攔截案例的文章就介紹到這了,更多相關(guān)Springboot登錄關(guān)于cookie和session攔截內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. idea設(shè)置提示不區(qū)分大小寫的方法2. .NET SkiaSharp 生成二維碼驗證碼及指定區(qū)域截取方法實現(xiàn)3. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))4. css代碼優(yōu)化的12個技巧5. CentOS郵件服務(wù)器搭建系列—— POP / IMAP 服務(wù)器的構(gòu)建( Dovecot )6. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容7. 原生JS實現(xiàn)記憶翻牌游戲8. Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)9. django創(chuàng)建css文件夾的具體方法10. IntelliJ IDEA創(chuàng)建web項目的方法
