SSM 攔截器驗證權限和登錄與注銷的實現


攔截器的作用在於,比如我們輸入 xxx.com/admin 發起請求進入 網站后台或者其他后台頁面。我們的攔截器會在 Controller  調用之前進行攔截,至於什么攔截,由我們來寫。比如,判斷用戶是否登錄(可以通過 session 判斷),如果沒有登錄,我們讓它跳轉到登錄頁面。

轉載 https://liuyanzhao.com/6300.html 

一、攔截器的基本使用

1、新建一個 攔截器

SecurityInterceptor.java

 
  1. package com.liuyanzhao.blog.Interceptor;
  2. import org.springframework.web.servlet.HandlerInterceptor;
  3. import org.springframework.web.servlet.ModelAndView;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. public class SecurityInterceptor implements HandlerInterceptor {
  7.     @Override
  8.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
  9.         System.out.println("SecurityInterceptor...preHandle...");
  10.         //這里可以根據session的用戶來判斷角色的權限,根據權限來轉發不同的頁面
  11.         if(request.getSession().getAttribute("userId") == null) {
  12.             request.getRequestDispatcher("/login").forward(request,response);
  13.             return false;
  14.         }
  15.         return true;
  16.     }
  17.     @Override
  18.     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  19.     }
  20.     @Override
  21.     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  22.     }
  23. }

判斷是否有 userId 這個session,如果沒有(或者過期了)轉發到登錄頁面

 

2、配置 springmvc.xml

通過使用 mvc:interceptors 標簽來聲明需要加入到SpringMVC攔截器鏈中的攔截器。

 
  1. <mvc:interceptors>
  2.       <mvc:interceptor>
  3.           <mvc:mapping path="/admin"/>
  4.           <bean class="com.liuyanzhao.blog.Interceptor.SecurityInterceptor"/>
  5.       </mvc:interceptor>
  6.       <mvc:interceptor>
  7.           <mvc:mapping path="/admin/**"/>
  8.           <bean class="com.liuyanzhao.blog.Interceptor.SecurityInterceptor"/>
  9.       </mvc:interceptor>
  10.   </mvc:interceptors>

 

只需兩步,我們已經能成功攔截  /admin 和其其前綴的如 /admin/article 等其他所有路徑啦。

 

二、登錄實現

登錄主要是驗證該用戶是否存在,密碼是否正確。然后添加 session 和頁面跳轉

1、登錄表單

login.jsp

 
  1. <%
  2.          String username = "";
  3.          String password = "";
  4.          //獲取當前站點的所有Cookie
  5.          Cookie[] cookies = request.getCookies();
  6.          for (int i = 0; i cookies.length; i++) {//對cookies中的數據進行遍歷,找到用戶名、密碼的數據
  7.              if ("username".equals(cookies[i].getName())) {
  8.                     username = cookies[i].getValue();
  9.              } else if ("password".equals(cookies[i].getName())) {
  10.                  password = cookies[i].getValue();
  11.              }
  12.          }
  13. %>
  14.     <form name="loginForm" id="loginForm"  method="post">
  15.                 <input type="text" name="username" id="user_login"
  16.                            class="input" value="<%=username%>" size="20" required/></label>
  17.                 <input type="password" name="password" id="user_pass"
  18.                            class="input" value="<%=password%>" size="20" required/>
  19.                  <input name="rememberme" type="checkbox" id="rememberme" value="1" /> 記住密碼
  20.                 <input type="button" name="wp-submit" id="submit-btn" class="button button-primary button-large" value="登錄" />
  21.     </form>

為了代碼簡潔,這里去掉了多余的標簽和屬性。我這里是扒了 wordpress 的登錄頁面,這里也用到了 cookie 。

SSM博客實戰(9)-攔截器驗證權限和登錄與注銷的實現

注意:這里的 form 表單里沒有 action 屬性,最終發送數據通過 ajax 。同樣,也沒有 submit 按鈕,為了防止 ajax+form+submit 導致 success 里無法頁面跳轉。

 

2、js 代碼

 
  1. <%--登錄驗證--%>
  2.  $("#submit-btn").click(function () {
  3.      var user = $("#user_login").val();
  4.      var password = $("#user_pass").val();
  5.      if(user=="") {
  6.          alert("用戶名不可為空!");
  7.      } else if(password==""){
  8.          alert("密碼不可為空!");
  9.      } else {
  10.          $.ajax({
  11.              async: false,//同步,待請求完畢后再執行后面的代碼
  12.              type: "POST",
  13.              url: '${pageContext.request.contextPath}/loginVerify',
  14.              contentType: "application/x-www-form-urlencoded; charset=utf-8",
  15.              data: $("#loginForm").serialize(),
  16.              dataType: "json",
  17.              success: function (data) {
  18.                  if(data.code==0) {
  19.                      alert(data.msg);
  20.                  } else {
  21.                      window.location.href="${pageContext.request.contextPath}/admin";
  22.                  }
  23.              },
  24.              error: function () {
  25.                  alert("數據獲取失敗")
  26.              }
  27.          })
  28.      }
  29.  })

這里 ajax 使用同步,防止出現后台沒有返回值,就執行了后面的js代碼,進而出現 ajax 執行 error:function() 里的代碼。數據類型使用 json,當然也可以使用 text,只不過 text 只能 返回普通的字符串。

最后,如果驗證通過,將跳轉到 xxx.com/admin 頁面(當然后台需要加入session,否則攔截器會攔截)。

 

3、控制器代碼

 
  1. //登錄頁面顯示
  2.     @RequestMapping("/login")
  3.     public ModelAndView loginView() {
  4.         ModelAndView modelAndView = new ModelAndView();
  5.         modelAndView.setViewName("/Admin/login");
  6.         return modelAndView;
  7.     }
  8.     //登錄驗證
  9.     @RequestMapping(value = "/loginVerify",method = RequestMethod.POST)
  10.     @ResponseBody
  11.     public String loginVerify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  12.         Map<String, Object> map = new HashMap<String, Object>();
  13.         String username = request.getParameter("username");
  14.         String password = request.getParameter("password");
  15.         String rememberme = request.getParameter("rememberme");
  16.         UserCustom userCustom = userService.getUserByNameOrEmail(username);
  17.         if(userCustom==null) {
  18.             map.put("code",0);
  19.             map.put("msg","用戶名無效!");
  20.         } else if(!userCustom.getUserPass().equals(password)) {
  21.             map.put("code",0);
  22.             map.put("msg","密碼錯誤!");
  23.         } else {
  24.             //登錄成功
  25.             map.put("code",1);
  26.             map.put("msg","");
  27.             //添加session
  28.             request.getSession().setAttribute("user", userCustom);
  29.             //添加cookie
  30.             if(rememberme!=null) {
  31.                 //創建兩個Cookie對象
  32.                 Cookie nameCookie = new Cookie("username", username);
  33.                 //設置Cookie的有效期為3天
  34.                 nameCookie.setMaxAge(60 * 60 * 24 * 3);
  35.                 Cookie pwdCookie = new Cookie("password", password);
  36.                 pwdCookie.setMaxAge(60 * 60 * 24 * 3);
  37.                 response.addCookie(nameCookie);
  38.                 response.addCookie(pwdCookie);
  39.             }
  40.         }
  41.         String result = new JSONObject(map).toString();
  42.         return result;
  43.     }

這里登錄驗證方法內,getUserByNameOrEmail() 方法用來從數據庫里查找是否有該用戶(用戶名或者郵箱)。如果有,而且密碼正確,添加一條 session,要和攔截器里寫的一致哦。並將信息添加到 Map 中,然后轉成 JSON 數據,這里需要導入 對應JSON 的jar 哦。

 
  1. <dependency>
  2.   <groupId>org.json</groupId>
  3.   <artifactId>json</artifactId>
  4.   <version>20170516</version>
  5. </dependency>

 

4、Service 和 DAO

這里就不貼 Service 和 Dao 的代碼了,主要就是根據 字符串查找用戶的操作啦。

 

 

三、注銷實現

注銷就比較簡單了,清除 session 就行了。

1、jsp 頁面

 
  1. <href="${pageContext.request.contextPath}/admin/logout">退了</a>

 

2、控制器代碼

 
  1. //退出登錄
  2.    @RequestMapping(value = "/admin/logout")
  3.    public String logout(HttpSession session) throws Exception {
  4.        session.removeAttribute("userId");
  5.        session.invalidate();
  6.        return "redirect:/login";
  7.    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM