SprimgMVC学习笔记(十)—— 拦截器
一、?什么是攔截器?
Spring MVC中的攔截器(Interceptor)類似于Servlet中的過濾器(Filter),它主要用于攔截用戶請求并作相應的處理。例如通過攔截器可以進行權限驗證、記錄請求信息的日志、判斷用戶是否登錄等。
要使用Spring MVC中的攔截器,就需要對攔截器類進行定義和配置。通常攔截器可以通過實現HandlerInterceptor接口,或繼承HandlerInterceptor接口的實現類(如HandlerInterceptorAdapter)來定義。
public class HandlerInterceptor1 implements HandlerInterceptor {// controller執行后且視圖返回后調用此方法// 這里可得到執行controller時的異常信息// 這里可記錄操作日志 @Overridepublic void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)throws Exception {System.out.println("HandlerInterceptor1....afterCompletion");}// controller執行后但未返回視圖前調用此方法// 這里可在返回用戶前對模型數據進行加工處理,比如這里加入公用信息以便頁面顯示 @Overridepublic void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)throws Exception {System.out.println("HandlerInterceptor1....postHandle");}// Controller執行前調用此方法// 返回true表示繼續執行,返回false中止執行// 這里可以加入登錄校驗、權限攔截等 @Overridepublic boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {System.out.println("HandlerInterceptor1....preHandle");// 設置為true,測試使用return true;} }?二、攔截器配置
上面定義的攔截器再復制一份HandlerInterceptor2,注意新的攔截器修改代碼:
System.out.println("HandlerInterceptor2....preHandle");在springmvc.xml中配置攔截器:
<mvc:interceptors><mvc:interceptor><!-- 所有請求都進入攔截器 --><mvc:mapping path="/**"/><!-- 配置具體的攔截器 --><bean class="cn.itcast.ssm.interceptor.HandlerInterceptor1"></bean></mvc:interceptor><mvc:interceptor><!-- 所有請求都進入攔截器 --><mvc:mapping path="/**"/><!-- 配置具體的攔截器 --><bean class="cn.itcast.ssm.interceptor.HandlerInterceptor2"></bean></mvc:interceptor></mvc:interceptors>?三、測試
3.1 正常流程測試
瀏覽器訪問地址:http://127.0.0.1:8080/springmvc-web/itemList.action
控制臺打印:
3.2 中斷流程測試
瀏覽器訪問地址:http://127.0.0.1:8080/springmvc-web/itemList.action
HandlerInterceptor1的preHandler方法返回false,HandlerInterceptor2返回true:
HandlerInterceptor1的preHandler方法返回true,HandlerInterceptor2返回false:
3.3 結果分析
從日志看出第一個攔截器的preHandler方法返回false后第一個攔截器只執行了preHandler方法,其它兩個方法沒有執行,第二個攔截器的所有方法不執行,且Controller也不執行了。
第二個攔截器的preHandler方法返回false后第一個攔截器的postHandler沒有執行,第二個攔截器的postHandler和afterCompletion沒有執行,且controller也不執行了。
總結:
preHandle按攔截器定義順序調用
postHandler按攔截器定義逆序調用
afterCompletion按攔截器定義逆序調用
postHandler在攔截器鏈內所有攔截器返成功調用
afterCompletion只有preHandle返回true才調用
四、攔截器應用
4.1 處理流程
1、有一個登錄頁面,需要寫一個Controller訪問登錄頁面
2、登錄頁面有一提交表單的動作。需要在Controller中處理。
a) 判斷用戶名密碼是否正確(在控制臺打印)
b) 如果正確,向session中寫入用戶信息(寫入用戶名username)
c) 跳轉到商品列表
3、攔截器
a) 攔截用戶請求,判斷用戶是否登錄(登錄請求不能攔截)
b) 如果用戶已經登錄。放行
c) 如果用戶未登錄,跳轉到登錄頁面。
4.2 編寫登錄jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body><form action="${pageContext.request.contextPath }/user/login.action"> <label>用戶名:</label> <br> <input type="text" name="username"> <br> <label>密碼:</label> <br> <input type="password" name="password"> <br> <input type="submit"></form></body> </html>4.3 用戶登錄Controller
@Controller @RequestMapping("user") public class UserController {/*** 跳轉到登錄頁面* @return*/@RequestMapping("toLogin")public String toLogin(){return "login";}@RequestMapping("login")public String login(String username,String password,HttpSession session){// 校驗用戶登錄 System.out.println(username);System.out.println(password);// 把用戶放到session中session.setAttribute("username", username);return "redirect:/item/itemList.action";} }4.4 編寫攔截器
public class LoginHandlerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {// 從request中獲取sessionHttpSession session = request.getSession();// 從session中獲取usernameObject username = session.getAttribute("username");// 判斷username是否為nullif(username != null){// 如果不為空,則放行return true;}else{// 如果為空則跳轉到登錄頁面response.sendRedirect(request.getContextPath() + "/user/toLogin.action");}return false;}@Overridepublic void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)throws Exception {}@Overridepublic void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)throws Exception {}}4.5 配置攔截器
只能攔截商品的url,所以需要修改ItemController,讓所有的請求都必須以item開頭,如下圖:
在springmvc.xml配置攔截器:
<mvc:interceptor><!-- 配置商品被攔截器攔截 --><mvc:mapping path="/item/**" /><!-- 配置具體的攔截器 --><bean class="cn.itcast.ssm.interceptor.LoginHandlerInterceptor" /> </mvc:interceptor>轉載于:https://www.cnblogs.com/yft-javaNotes/p/10216867.html
總結
以上是生活随笔為你收集整理的SprimgMVC学习笔记(十)—— 拦截器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET 中使用 Mutex 进行跨越进
- 下一篇: 总结day11 ----函数的学习(2)