SpringMVC之攔截器的的配置和使用


攔截器與過濾器的區別:攔截器只能攔截controller的請求,過濾器可以過濾所有請求

(1)實現HandlerInterceptor接口

   在執行控制器中的方法之前執行preHandle()中的方法

 1 package com.eu.weh.web;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 import javax.servlet.http.HttpSession;
 6 
 7 import org.springframework.web.servlet.HandlerInterceptor;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 import com.eu.weh.bean.User;
11 
12 /**
13  * 
14  * @ClassName: LoginInterceptor
15  * @Description: 登錄攔截器
16  * @author Administrator
17  * @date 2019年4月29日 上午10:31:25
18  *
19  */
20 public class LoginInterceptor implements HandlerInterceptor {
21 
22     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
23             throws Exception {
24         
25         //判斷當前用戶是否已經登錄
26         HttpSession session = request.getSession();
27         User loginUser = (User) session.getAttribute("dbUser");
28         if (loginUser == null) {
29             String path = session.getServletContext().getContextPath();
30             response.sendRedirect(path+"/login");
31             return false;
32         }else {
33             return true;
34         }
35     }
36 
37     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
38             ModelAndView modelAndView) throws Exception {
39         
40     }
41 
42     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
43             throws Exception {
44         
45     }
46 
47 }

(2)SpringMVC配置文件

 1 <mvc:interceptors>
 2         <mvc:interceptor>
 3             <mvc:mapping path="/**" />
 4             <mvc:exclude-mapping path="/login" />
 5             <mvc:exclude-mapping path="/doAJAXlogin" />
 6             <mvc:exclude-mapping path="/bootstrap/**" />
 7             <mvc:exclude-mapping path="/css/**" />
 8             <mvc:exclude-mapping path="/fonts/**" />
 9             <mvc:exclude-mapping path="/img/**" />
10             <mvc:exclude-mapping path="/jquery/**" />
11             <mvc:exclude-mapping path="/layer/**" />
12             <mvc:exclude-mapping path="/script/**" />
13             <mvc:exclude-mapping path="/ztree/**" />
14             <bean class="com.eu.weh.web.LoginInterceptor"></bean>
15         </mvc:interceptor>
16     </mvc:interceptors>

 


免責聲明!

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



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