1. 程式人生 > >SpringMVC 攔截器

SpringMVC 攔截器

div path 調用 打開 lns -m www 輸出 編程)

類似於Servlet開發中的過濾器Filter,用於對處理器進行預處理和後處理.

常用場景:

1、日誌記錄:記錄請求信息的日誌,以便進行信息監控、信息統計、計算PV(Page View)等。

2、權限檢查:如登錄檢測,進入處理器檢測檢測是否登錄,如果沒有直接返回到登錄頁面;

3、性能監控:有時候系統在某段時間莫名其妙的慢,可以通過攔截器在進入處理器之前記錄開始時間,在處理完後記錄結束時間,從而得到該請求的處理時間(如果有反向代理,如apache可以自動記錄);

4、通用行為:讀取cookie得到用戶信息並將用戶對象放入請求,從而方便後續流程使用,還有如提取Locale、Theme信息等,只要是多個處理器都需要的即可使用攔截器實現。

5、OpenSessionInView:如Hibernate,在進入處理器打開Session,在完成後關閉Session。

…………本質也是AOP(面向切面編程),也就是說符合橫切關註點的所有功能都可以放入攔截器實現。

技術分享
package org.springframework.web.servlet;
public interface HandlerInterceptor {
    boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, 
            Object handler) 
            throws Exception;

    void postHandle(
            HttpServletRequest request, HttpServletResponse response, 
            Object handler, ModelAndView modelAndView) 
            throws Exception;

    void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, 
            Object handler, Exception ex)
            throws Exception;
} 
技術分享

preHandle預處理回調方法,實現處理器的預處理(如登錄檢查),第三個參數為響應的處理器(如我們上一章的Controller實現);

返回值:true表示繼續流程(如調用下一個攔截器或處理器);

false表示流程中斷(如登錄檢查失敗),不會繼續調用其他的攔截器或處理器,此時我們需要通過response來產生響應;

postHandle後處理回調方法,實現處理器的後處理(但在渲染視圖之前),此時我們可以通過modelAndView(模型和視圖對象)對模型數據進行處理或對視圖進行處理,modelAndView也可能為null。

afterCompletion

整個請求處理完畢回調方法,即在視圖渲染完畢時回調,如性能監控中我們可以在此記錄結束時間並輸出消耗時間,還可以進行一些資源清理,類似於try-catch-finally中的finally,但僅調用處理器執行鏈中preHandle返回true的攔截器的afterCompletion

登陸檢測Demo:

處理攔截器,攔截檢測除了/login之外所有url是否登陸,未登錄都將其跳轉到/login

技術分享
package com.test.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class UserSecurityInterceptor implements HandlerInterceptor{

    private List<String> excludedUrls;
    
    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

    public List<String> getExcludedUrls() {
        return excludedUrls;
    }

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        
        String requestUri = arg0.getRequestURI();
        for (String url : excludedUrls) {
            if (requestUri.endsWith(url)) {
                return true;
            }
        }
        
        HttpSession session = arg0.getSession();
        if (session.getAttribute("user") == null) {
            System.out.println(arg0.getContextPath());
            arg1.sendRedirect(arg0.getContextPath() + "/login");
        }
        return false;
    }

}
技術分享
excludedUrls是要放行的url,在spring配置.此外要註意一些類似jpg,css,js靜態文件被攔截的處理
技術分享
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
        
    <!-- 自動掃描的包名 -->
    <context:component-scan base-package="com.test.controller" /> 
    <!-- 默認的註解映射的支持 -->
    <mvc:annotation-driven />
    
    <!-- 配置資源文件,防止被攔截 -->
    <mvc:resources location="/WEB-INF/view/image/" mapping="/image/**"/>  
    <mvc:resources location="/WEB-INF/view/js/" mapping="/js/**"/>  
    <mvc:resources location="/WEB-INF/view/css/" mapping="/css/**"/>

    <!-- 攔截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*" />
            <bean class="com.test.interceptor.UserSecurityInterceptor">
                <property name="excludedUrls">
                    <list>
                        <value>/login</value>
                    </list>
                </property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <!-- 視圖解釋類 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
技術分享

控制器代碼:

@RequestMapping("/login")
    public void login() {
        return;
    }

SpringMVC 攔截器