Spring MVC Handler Interceptor does not run

末鹿安然 提交于 2019-12-05 16:15:12

Ok, I found solution, because my path is defined with following :

<servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

And this is how my controller looks like

@Controller
@RequestMapping(value = "/api")
public class ApiController {
 @RequestMapping(value = "/01/status", method = RequestMethod.GET)
    @ResponseBody
    public ServerStatusJSON getStatus(HttpServletResponse response) {
        ...
    }
}

The working configuration for this address : http://localhost:8080/myserver/rest/api/01/status is as following :

<mvc:interceptors>
 <mvc:interceptor>
   <mvc:mapping path="/api/01/status" />
   <bean class="cz.coffeeexperts.feedback.server.web.interceptors.RestAuthorizationInterceptor" />
 </mvc:interceptor>
</mvc:interceptors>    

PS : My thanks to geoand, he pushed me to the right way.

Richard Xue

I solved this problem by changing the value of mvc:mapping. My working configuration is:

    <mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="cn.mmd.micro.common.TokenInterceptor">
            <property name="excludeUrls">
                <list>
                    <value>/app/token</value>
                </list>
            </property>
        </bean>
    </mvc:interceptor>
</mvc:interceptors>

Providing additional explanation as to why this method worked for libik. As he has mentioned his controller looks like -

@Controller
@RequestMapping(value = "/api")
public class ApiController {
 @RequestMapping(value = "/01/status", method = RequestMethod.GET)
    @ResponseBody
    public ServerStatusJSON getStatus(HttpServletResponse response) {
        ...
    }
}

And also remember interceptors are at HandlerMapping level. In this case it would be RequestMappingHandlerMapping (Spring 3.1+ with mvc:annotation-driven) or DefaultAnnotationHandlerMapping. and the mapping here would be for /api/01/status which is precisely what he has done.

<mvc:interceptors>
 <mvc:interceptor>
   <mvc:mapping path="/api/01/status" />
   <bean class="cz.coffeeexperts.feedback.server.web.interceptors.RestAuthorizationInterceptor" />
 </mvc:interceptor>
</mvc:interceptors>   

If you want it to be applied for all patterns you can simply do <mvc:mapping path="/**"/> - this will match all URLs (including subpaths) or you can simply invoke interceptors for all HandlerMappings -

<mvc:interceptors> 
<bean class="cz.coffeeexperts.feedback.server.web.interceptors.RestAuthorizationInterc‌​eptor" /> 
</mvc:interceptors>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!