天天看點

SpringMVC的攔截器入門程式

01-SpringMVC攔截器-攔截器的作用(了解)

Spring MVC 的攔截器類似于 Servlet 開發中的過濾器 Filter,用于對處理器進行預處理和後處理。

将攔截器按一定的順序聯結成一條鍊,這條鍊稱為攔截器鍊(InterceptorChain)。在通路被攔截的方法或字段時,攔截器鍊中的攔截器就會按其之前定義的順序被調用。攔截器也是AOP思想的具體實作。

02-SpringMVC攔截器-interceptor和filter差別(了解,記憶)

關于interceptor和filter的差別,如圖所示:

SpringMVC的攔截器入門程式

03-SpringMVC攔截器-快速入門(應用)

自定義攔截器很簡單,隻有如下三步:

①建立攔截器類實作HandlerInterceptor接口

②配置攔截器

③測試攔截器的攔截效果

編寫攔截器:

public class MyInterceptor1 implements HandlerInterceptor {
    //目标方法執行之前 執行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user1 = session.getAttribute("user1");
        if(user1!=null){
            System.out.println("preHandle--------------------");
            return true;
        }else{
            response.sendRedirect("/login/login2.jsp");
            return false;
        }
    }
    //在目标方法執行之後,視圖對象傳回之前執行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle-------------------");
    }
    //在流程都執行完畢後,執行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion-------------");
    }
}
           

配置:在SpringMVC的配置檔案中配置

<!--配置攔截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--對哪些資源執行攔截操作-->
            <mvc:mapping path="/**"/>
            <bean class="com.ll.interceptor.MyInterceptor1"/>
        </mvc:interceptor>
    </mvc:interceptors>
           

編寫測試程式測試:

編寫Controller,發請求到controller,跳轉頁面

@Controller
public class TargetController {

    @RequestMapping("/target")
    public ModelAndView show(){
        System.out.println("目标資源執行......");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name","baby");
        //跳轉到根目錄index.jsp
        modelAndView.setViewName("/index.jsp");
        return modelAndView;
    }

}
           

頁面

<html>
<body>
<h2>Hello World! ${name}</h2>
</body>
</html>
           

繼續閱讀