簡體   English   中英

在Spring MVC中設置攔截器

[英]Set up an interceptor in Spring MVC

根據http://patrickgrimard.com/2013/12/12/cross-origin-resource-sharing-cors-requests-with-spring的說明 ,我正在嘗試應對SOP,並且需要設置過濾器和攔截器-mvc / 我在web.xml中設置了過濾器:

<filter>
    <filter-name>simpleCORSFilter</filter-name>
    <filter-class>base.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>simpleCORSFilter</filter-name>
    <servlet-name>rest</servlet-name>
</filter-mapping>

SimpleCORSFilter在哪里

@Component
public class SimpleCORSFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest req,
        HttpServletResponse res, FilterChain filterChain)
        throws ServletException, IOException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods",
            "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");  
    filterChain.doFilter(req, res);
}

之所以有效,是因為我的測試POST請求已被捕獲和處理。 現在,我嘗試配置以下攔截器:

@Component
public class SimpleCORSInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {
    response.addHeader("Access-Control-Allow-Origin", "*");
    return true;
}
}

並且我在rest-servlet.xml中添加了以下配置(由於正確調用了REST服務,因此可以使用):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.lh.clte.web" />
<mvc:annotation-driven />

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/*" />
        <bean class="base.SimpleCORSInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>

但是,未調用重寫的方法。 我想念什么?

在本文中,過濾器用於使用OPTION方法的請求,而攔截器則用於“實際”調用。 在您的示例中,所有請求都將由過濾器和攔截器處理。 因此,您不需要攔截器。

此外,僅在存在處理請求的控制器方法時才調用攔截器。 當您調用未映射的URL時,則不會調用攔截器。

順便說一句:不需要@Component

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM