【问题标题】:spring - method for all requestspring - 所有请求的方法
【发布时间】:2014-12-27 17:34:06
【问题描述】:

有一种方法(在 Spring 中)可以定义一个必须为所有请求调用的方法,类似于 @modelAttribute???

我想定义一个方法来对每个请求进行检查并放入会话对象,方法是一样的

在这种方法中,我将收到“Principal”(null,在身份验证之前和用户名...ecc之后)

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    一种方法是使用 org.springframework.web.servlet.handler.HandlerInterceptorAdapter。

    看看这篇文章:

    http://www.journaldev.com/2676/spring-mvc-interceptors-example-handlerinterceptor-and-handlerinterceptoradapter

    只需创建一个扩展它的类并使其成为组件。然后您可以将拦截器映射到您的 applicatioContext.xml 中的特定 url 模式。

     <mvc:interceptors>  
     <mvc:interceptor>  
         <mvc:mapping path="/*.svc"/>  
        <bean class="com.netsoft.skydive.controllers.SecuredApiEndpoint"></bean>  
     </mvc:interceptor>  
    </mvc:interceptors>  
    

    【讨论】:

      【解决方案2】:

      正如另一个答案中提到的 - 只需使用 HandlerInterceptor 并从例如继承HandlerInterceptorAdapter。最方便的方法可能是使用 Spring 的 java 配置,如下代码示例所示:

      @Configuration
      @EnableWebMvc
      @ComponentScan(basePackages="my.base.package")
      public class MyWebApplicationConfig extends WebMvcConfigurerAdapter {
      
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
              registry.addInterceptor(new HandlerInterceptorAdapter() {
                  @Override
                  public boolean preHandle(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final Object o) throws Exception {
                      // Do stuff with your interceptor
                      return true;
      
                  }
              }).addPathPatterns("/**");
          }
      }
      

      有关这方面的更多信息,请查看优秀的JavaDoc

      【讨论】:

        猜你喜欢
        • 2017-09-03
        • 2019-03-29
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-23
        相关资源
        最近更新 更多