【Java.Spring.MVC】使用HandlerInterceptor攔截請求

來源:互聯網
上載者:User

Spring的handler mapping機制提供了handler interceptors,可以用來為特定的請求添加特定的功能,如,檢測資金額等。

handler mapping的攔截器必須實現HandlerInterceptor的介面。該介面定義了三個方法:

preHandler() - 在實際的handler被執行前被調用 postHandler() - 在handler被執行後被調用 afterCompletion() - 當request處理完成後被調用

preHandler()方法返回一個布爾值。可以使用該方法繼續或者中斷執行鏈。當返回true,繼續執行鏈;如果返回false,則停止後續的執行。

Interceptor使用interceptors屬性進行配置,該屬性為HandlerMapping類的屬性。

例如:

<beans>    <bean id="handlerMapping"            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">        <property name="interceptors">            <list>                <ref bean="officeHoursInterceptor"/>            </list>        </property>    </bean>    <bean id="officeHoursInterceptor"            class="samples.TimeBasedAccessInterceptor">        <property name="openingTime" value="9"/>        <property name="closingTime" value="18"/>    </bean><beans>
package samples;public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {    private int openingTime;    private int closingTime;    public void setOpeningTime(int openingTime) {        this.openingTime = openingTime;    }    public void setClosingTime(int closingTime) {        this.closingTime = closingTime;    }    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,            Object handler) throws Exception {        Calendar cal = Calendar.getInstance();        int hour = cal.get(HOUR_OF_DAY);        if (openingTime <= hour && hour < closingTime) {            return true;        }        response.sendRedirect("http://host.com/outsideOfficeHours.html");        return false;    }}

該handler請求的任何request都會被TimeBasedAccessInterceptor所中斷。

使用是配置HandlerInterceptorAdaptor類作為中斷器的基類(HandlerInterceptor介面的實作類別)。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.