JavaWeb使用Session和Cookie實(shí)現(xiàn)登錄認(rèn)證
后臺(tái)管理頁面往往需要登錄才可以進(jìn)行操作,這時(shí)就需要Seession來記錄登錄狀態(tài)
要實(shí)現(xiàn)起來也是非常簡(jiǎn)單,只需要自定義一個(gè)HandlerInterceptor就行了
自定義的HandlerInterceptor也只有短短幾行代碼
public class LoginInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception err) throws Exception { } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { //獲取session里的登錄狀態(tài)值 String str = (String) request.getSession().getAttribute("isLogin"); //如果登錄狀態(tài)不為空則返回true,返回true則會(huì)執(zhí)行相應(yīng)controller的方法 if(str!=null){ return true; } //如果登錄狀態(tài)為空則重定向到登錄頁面,并返回false,不執(zhí)行原來controller的方法 response.sendRedirect("/backend/loginPage"); return false; } }
Controller代碼
@Controller @RequestMapping("/backend") public class BackendController { @RequestMapping(value = "/loginPage", method = {RequestMethod.GET}) public String loginPage(HttpServletRequest request,String account, String password){ return "login"; } @RequestMapping(value = "/login", method = {RequestMethod.POST}) public String login(HttpServletRequest request,RedirectAttributes model, String account, String password){ //驗(yàn)證賬號(hào)密碼,如果符合則改變session里的狀態(tài),并重定向到主頁 if ("jack".equals(account)&&"jack2017".equals(password)){ request.getSession().setAttribute("isLogin","yes"); return "redirect:IndexPage"; }else { //密碼錯(cuò)誤則重定向回登錄頁,并返回錯(cuò)誤,因?yàn)槭侵囟ㄏ蛩玫絉edirectAttributes model.addFlashAttribute("error","密碼錯(cuò)誤"); return "redirect:loginPage"; } } //登出,移除登錄狀態(tài)并重定向的登錄頁 @RequestMapping(value = "/loginOut", method = {RequestMethod.GET}) public String loginOut(HttpServletRequest request) { request.getSession().removeAttribute("isLogin"); return "redirect:loginPage"; } @RequestMapping(value = "/IndexPage", method = {RequestMethod.GET}) public String IndexPage(HttpServletRequest request){ return "Index"; } }
spring的配置
<!--省略其他基本配置--> <!-- 配置攔截器 --> <mvc:interceptors> <!-- 配置登陸攔截器 --> <mvc:interceptor> <!--攔截后臺(tái)頁面的請(qǐng)求--> <mvc:mapping path="/backend/**"/> <!--不攔截登錄頁和登錄的請(qǐng)求--> <mvc:exclude-mapping path="/backend/loginPage"/> <mvc:exclude-mapping path="/backend/login"/> <bean class="com.ima.Interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
一個(gè)簡(jiǎn)單的Session實(shí)現(xiàn)登錄認(rèn)證系統(tǒng)就這樣完成了,如果想登錄狀態(tài)退出瀏覽器后仍保留一段時(shí)間的可以將Session改為Cookie
一般情況下我們都會(huì)使用Cookie
Cookie和Session的方法差不多
使用Cookie的自定義HandlerInterceptor
public class LoginInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception err) throws Exception { } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { // 獲取request的cookie Cookie[] cookies = request.getCookies(); if (null==cookies) { System.out.println("沒有cookie=============="); } else { // 遍歷cookie如果找到登錄狀態(tài)則返回true執(zhí)行原來controller的方法 for(Cookie cookie : cookies){ if(cookie.getName().equals("isLogin")){ return true; } } } // 沒有找到登錄狀態(tài)則重定向到登錄頁,返回false,不執(zhí)行原來controller的方法 response.sendRedirect("/backend/loginPage"); return false; } }
Controller的變化也不大
@Controller @RequestMapping("/backend") public class BackendController { @RequestMapping(value = "/loginPage", method = {RequestMethod.GET}) public String loginPage(HttpServletRequest request, String account, String password) { return "login"; } @RequestMapping(value = "/login", method = {RequestMethod.POST}) public String login(HttpServletRequest request, HttpServletResponse response, RedirectAttributes model, String account, String password) { if ("edehou".equals(account) && "aidou2017".equals(password)) { Cookie cookie = new Cookie("isLogin", "yes"); cookie.setMaxAge(30 * 60);// 設(shè)置為30min cookie.setPath("/"); response.addCookie(cookie); return "redirect:IndexPage"; } else { model.addFlashAttribute("error", "密碼錯(cuò)誤"); return "redirect:loginPage"; } } @RequestMapping(value = "/logOut", method = {RequestMethod.GET}) public String loginOut(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("isLogin")) { cookie.setValue(null); cookie.setMaxAge(0);// 立即銷毀cookie cookie.setPath("/"); response.addCookie(cookie); break; } } return "redirect:loginPage"; } @RequestMapping(value = "/IndexPage", method = {RequestMethod.GET}) public String IndexPage(HttpServletRequest request) { return "Index"; } }
spring的配置和之前的一模一樣
注意
這里只是演示,建議在實(shí)際項(xiàng)目中Cookie的鍵和值要經(jīng)過特殊處理,否則會(huì)引發(fā)安全問題
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java Bean與Map之間相互轉(zhuǎn)化的實(shí)現(xiàn)方法
這篇文章主要介紹了Java Bean與Map之間相互轉(zhuǎn)化的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01java編程之基于SpringBoot框架實(shí)現(xiàn)掃碼登錄
本文將介紹基于SpringBoot + Vue + Android實(shí)現(xiàn)的掃碼登錄demo的總體思路,文中附含詳細(xì)示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09Java連接MySQL數(shù)據(jù)庫(kù)并實(shí)現(xiàn)數(shù)據(jù)交互功能
在現(xiàn)代應(yīng)用中,數(shù)據(jù)庫(kù)是不可或缺的一部分,Java 作為一種廣泛使用的編程語言,提供了豐富的 API 來與各種數(shù)據(jù)庫(kù)進(jìn)行交互,本文將詳細(xì)介紹如何在 Java 中連接 MySQL 數(shù)據(jù)庫(kù),并實(shí)現(xiàn)基本的數(shù)據(jù)交互功能,需要的朋友可以參考下2024-10-10Java實(shí)現(xiàn)STL中的全排列函數(shù)next_permutation()
在算法競(jìng)賽中,全排列問題是一個(gè)經(jīng)典且常見的題目,傳統(tǒng)的遞歸方法在處理較大的n時(shí)會(huì)遇到堆棧內(nèi)存限制的問題,本文介紹了一種避免遞歸,使用next_permutation函數(shù)實(shí)現(xiàn)全排列的方法,感興趣的朋友跟隨小編一起看看吧2024-09-09Java中通過jsch來連接遠(yuǎn)程服務(wù)器執(zhí)行l(wèi)inux命令
這篇文章主要介紹了Java中通過jsch來連接遠(yuǎn)程服務(wù)器執(zhí)行l(wèi)inux命令的相關(guān)資料,需要的朋友可以參考下2016-03-03