本篇文章主要介紹了JavaWeb使用Session和Cookie實現登入認證,具有一定的參考價值,有興趣的小夥伴可以參考一下。
後台管理頁面往往需要登入才能操作,這時就需要Seession來記錄登入狀態
要實現起來也是非常簡單,只需要自訂一個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里的登录状态值 String str = (String) request.getSession().getAttribute("isLogin"); //如果登录状态不为空则返回true,返回true则会执行相应controller的方法 if(str!=null){ return true; } //如果登录状态为空则重定向到登录页面,并返回false,不执行原来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){ //验证账号密码,如果符合则改变session里的状态,并重定向到主页 if ("jack".equals(account)&&"jack2017".equals(password)){ request.getSession().setAttribute("isLogin","yes"); return "redirect:IndexPage"; }else { //密码错误则重定向回登录页,并返回错误,因为是重定向所要要用到RedirectAttributes model.addFlashAttribute("error","密码错误"); return "redirect:loginPage"; } } //登出,移除登录状态并重定向的登录页 @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> <!--拦截后台页面的请求--> <mvc:mapping path="/backend/**"/> <!--不拦截登录页和登录的请求--> <mvc:exclude-mapping path="/backend/loginPage"/> <mvc:exclude-mapping path="/backend/login"/> <bean class="com.ima.Interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
一個簡單的Session實作登入認證系統就這樣完成了,如果想要登入狀態登出瀏覽器後仍保留一段時間的可以將Session改為Cookie
一般情況下我們都會使用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如果找到登录状态则返回true执行原来controller的方法 for(Cookie cookie : cookies){ if(cookie.getName().equals("isLogin")){ return true; } } } // 没有找到登录状态则重定向到登录页,返回false,不执行原来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);// 设置为30min cookie.setPath("/"); response.addCookie(cookie); return "redirect:IndexPage"; } else { model.addFlashAttribute("error", "密码错误"); 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的配置和之前的一模一樣
注意
這裡只是演示,建議在實際項目中Cookie的鍵和值要經過特殊處理,否則會引發安全性問題
以上是JavaWeb使用Session和Cookie實作登入認證的程式碼實例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!