web-dev-qa-db-fra.com

Spring MVC 3, Interceptor on all excluant certains chemins définis

Est-il possible d'appliquer un intercepteur à tous les contrôleurs et actions, à l'exception de certains qui sont définis?

Juste pour être clair, je ne suis pas intéressé à appliquer un intercepteur sur une liste de ceux définis. Je veux définir ceux à exclure.

Merci!

45
momomo

Depuis le printemps 3.2, ils ont ajouté cette fonctionnalité avec la balise

mvc:exclude-mapping

Voir cet exemple dans la documentation Spring:

<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<mvc:interceptor>
    <mvc:mapping path="/**"/>
    <mvc:exclude-mapping path="/admin/**"/>
    <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" />
</mvc:interceptor>
<mvc:interceptor>
    <mvc:mapping path="/secure/*"/>
    <bean class="org.example.SecurityInterceptor" />
</mvc:interceptor>

Voici le lien vers le doc

66
gamerkore

Pour Java, à partir de docs

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleInterceptor());
        registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
        registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
    }

}
22
Abdullah Khan

Lors de la configuration d'un intercepteur, vous pouvez spécifier un modèle de chemin. L'intercepteur sera appelé uniquement pour les contrôleurs dont le chemin correspond au modèle de chemin d'intercepteur.

réf: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config-interceptor

Mais comme vous l'avez probablement remarqué, le modèle de chemin ne prend pas en charge l'exclusion.

Je pense donc que la seule façon est de coder une liste noire de chemins à l'intérieur de l'intercepteur. Lorsque l'intercepteur est appelé, récupérez la HttpServletRequest.getRequestURI() et vérifiez si le chemin est sur liste noire ou non.

Vous pouvez créer la liste noire dans un @PostConstruct méthode annotée de l'intercepteur, et ainsi obtenir le chemin sur liste noire à partir d'un fichier de propriétés par exemple.

3
tbruyelle