怎么在春季启动项目中定制一个拦截器

  介绍

怎么在春季启动项目中定制一个拦截器?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

添加拦截器不仅是在WebConfiguration中定义bean,弹簧引导提供了基础类WebMvcConfigurerAdapter,我们项目中的WebConfiguration类需要继承这个类。

继承WebMvcConfigurerAdapter;

为LocaleChangeInterceptor添加@ bean定义,这仅仅是定义了一个拦截器Spring bean,但春天是引导不会自动将它加入到调用链中。

拦截器需要手动加入调用链。

修改后完整的WebConfiguration代码如下:

package  com.test.bookpub;      import  org.apache.catalina.filters.RemoteIpFilter;   import  org.springframework.context.annotation.Bean;   import  org.springframework.context.annotation.Configuration;   import  org.springframework.web.servlet.config.annotation.InterceptorRegistry;   import  org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;   import  org.springframework.web.servlet.i18n.LocaleChangeInterceptor;      @ configuration   public  class  WebConfiguration  extends  WebMvcConfigurerAdapter  {   ,,@Bean  public  RemoteIpFilter  remoteIpFilter (), {   ,,,return  new  RemoteIpFilter ();   ,,}      ,,@Bean  public  LocaleChangeInterceptor  localeChangeInterceptor (), {   ,,,return  new  LocaleChangeInterceptor ();   ,,}   ,,@Override  public  void  addInterceptors (InterceptorRegistry  registry  {   ,,,registry.addInterceptor (localeChangeInterceptor ());   ,,}   }

使用<代码> mvn spring-boot:运行运行程序,然后通过httpie访问<代码> http://localhost: 8080/书吗?语言环境=foo> Servlet.service (), for  servlet  [dispatcherServlet],拷贝context  with  path  [],   threw  exception  [Request  processing 失败;,nested  exception  is    java.lang.UnsupportedOperationException: Cannot  change  HTTP  accept    header 神;use  a  different  locale  resolution 策略),with  root 原因

关于怎么在春季启动项目中定制一个拦截器问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。

怎么在春季启动项目中定制一个拦截器