【问题标题】:Spring Boot Controller to handle all requests for preprocessing before forwarding to appropriate ControllerSpring Boot Controller 在转发到适当的 Controller 之前处理所有预处理请求
【发布时间】:2021-02-02 04:09:36
【问题描述】:

我的 Spring Boot 应用程序中有一系列 Rest API 控制器,其请求映射与某些 URL 匹配。 我需要更改我的实现以始终确保所有请求都有特定的自定义标头。如果标头不存在,我想使请求失败。如果是,我想转发到与我当前实现相同的适当控制器。

有没有办法在 Spring Boot 中完全不修改我现有的控制器来做到这一点?我是否可以尝试使用 Spring Security 之类的东西,即使我的标头与安全性完全无关?

谢谢。

【问题讨论】:

  • 请尝试使用拦截器。也就是实现一个HandlerInterceptor接口。该链接可能有助于tutorialspoint.com/spring_boot/spring_boot_interceptor.htm
  • 使用带有通用 url 模式的过滤器。它过滤控制器上的流量。
  • 谢谢你们。我将调查拦截器和过滤器的用法,并找出最适合我需要的。抱歉,我没有足够的声望来支持您的 cmets。

标签: java spring spring-boot api rest


【解决方案1】:

Web MVC 定义了一个名为“HandlerInterceptor”的抽象及其无操作实现HandlerInterceptorAdapter

所以你可以注册看起来像这样的bean:

@Component
public class RequestProcessingTimeInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        // check the headers, extract them from request, whatever
        return true; // if you want to proceed to controller
        return false;// otherwise :)
    }
}

这将指示 spring mvc 在流到达控制器之前调用该方法。

【讨论】:

    【解决方案2】:

    您可以将Filter 配置为@Service

    @Service
    @NoArgsConstructor @Log4j2
    public class FilterImpl implements Filter {
        @Override
        public void init(FilterConfig config) throws ServletException { }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain) throws IOException, ServletException {
            if (request.getHeader("required-header-name") != null) {
                chain.doFilter(request, response);
            } else {
                log.info("Rejected {}", request);
            }
        }
    
        @Override
        public void destroy() {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 1970-01-01
      • 2011-02-17
      • 2019-08-03
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多