Spring Boot RestController: 拦截传入的请求

5
我目前正在编写一种框架,使得其他人可以为其编写REST控制器。自然而然地,我希望这些“其他人”尽可能少地与我的代码互动。
具体来说,我想并且需要在请求被REST控制器处理之前访问请求数据(即RequestEntity)。有点像在控制器处理请求之前“拦截”请求,然后才让控制器处理它。
考虑以下代码:
@RestController
@RequestMapping("/")
public class MyController {

    @GetMapping("/")
    @ResponseBody
    public ResponseEntity<String> getSomething(RequestEntity requestEntity) {

        MyClass.doStuffWithRequestEntity(requestEntity);
        // ...

现在我需要的是能够自动调用ExternalClass.doStuffWithRequestEntity(requestEntity); 的方法,而不需要显式地调用它。是否有可能在某个类中调用某个方法(同时将 RequestEntity 传递给它!)而无需显式调用它?
此外,这个拦截器类还应该创建和配置一个对象,然后再将其提供给其余的控制器。
我想的是这样的:
class RestController {
    @RestController
    @RequestMapping("/")
    public class MyController {

        @GetMapping("/")
        @ResponseBody
        public ResponseEntity<String> getSomething() {

            MyClass x = MyClass.getInstanceCreatedByInterceptor();
        }
    }
}

并且

class Interceptor {
    public void doStuffWithRequestEntity(requestEntity) {

        MyClass x = new MyClass();
        x.fillObjectWithData();
    }
}

在处理之前执行。

这个想法是每一个(!)传入的请求都被解析并且它的内容被编码,而不需要rest控制器程序员关心这一点。他们只需要通过MyClass实例访问数据。

有没有办法做到这一点?


使用过滤器而不是RestController。在您的过滤器中注入一个请求范围的bean,并在此请求范围的bean中设置一个值。在“外部”rest控制器中注入相同的请求范围的bean,以获取过滤器中存储的值。 - JB Nizet
3个回答

7

Spring-boot允许我们配置自定义拦截器。通常在Spring Boot应用程序中,一切都是自动配置的,在这种情况下,我们可以通过使用WebMvcConfigurerAdapter来进行定制。只需扩展WebMvcConfigurerAdapter并在此类中提供所需的配置即可。

请记得添加@Configuration注解,以便在组件扫描期间Spring能够找到这个类。

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired 
  HandlerInterceptor customInjectedInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(...)
    ... 
    registry.addInterceptor(customInjectedInterceptor).addPathPatterns("/**");
  }
}

这是您通常向Spring Boot应用程序添加拦截器的方法。希望这可以帮助回答您的问题。
从Spring 5.x.x或Spring Boot 2开始,WebMvcConfigurerAdapter被标记为已弃用。WebMvcConfigurer接口(由抽象类WebMvcConfigurerAdapter实现)从Spring 5开始,包含其所有方法的默认实现。因此,该抽象适配器类被标记为已弃用。如果您喜欢,可以采用以下方式进行採用:
@Configuration
public WebConfig implements WebMvcConfigurer {
    // ...
}

1
WebMvcConfigurerAdapter 在5.0版本以后被标记为废弃。 - Xenonite
@Xenonite 感谢您指出这个问题。已经更新了答案。 - Ananthapadmanabhan

7

对于所有遇到相同或类似问题的人,这里提供一个带有拦截器的SpringBoot (2.1.4)应用程序的最小工作示例:

Minimal.java:

@SpringBootApplication
public class Minimal
{
    public static void main(String[] args)
    {
        SpringApplication.run(Minimal.class, args);
    }
}

MinimalController.java:

@RestController
@RequestMapping("/")
public class Controller
{
    @GetMapping("/")
    @ResponseBody
    public ResponseEntity<String> getMinimal()
    {
        System.out.println("MINIMAL: GETMINIMAL()");

        return new ResponseEntity<String>("returnstring", HttpStatus.OK);
    }
}

Config.java:

@Configuration
public class Config implements WebMvcConfigurer
{
    //@Autowired
    //MinimalInterceptor minimalInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(new MinimalInterceptor());
    }
}

MinimalInterceptor.java:

public class MinimalInterceptor extends HandlerInterceptorAdapter
{
    @Override
    public boolean preHandle(HttpServletRequest requestServlet, HttpServletResponse responseServlet, Object handler) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR PREHANDLE CALLED");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR POSTHANDLE CALLED");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED");
    }
}

功能如广告所述

输出将会给你类似于:

> Task :Minimal.main()

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-04-29 11:53:47.560  INFO 4593 --- [           main] io.minimal.Minimal                       : Starting Minimal on y with PID 4593 (/x/y/z/spring-minimal/build/classes/java/main started by x in /x/y/z/spring-minimal)
2019-04-29 11:53:47.563  INFO 4593 --- [           main] io.minimal.Minimal                       : No active profile set, falling back to default profiles: default
2019-04-29 11:53:48.745  INFO 4593 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-04-29 11:53:48.780  INFO 4593 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-04-29 11:53:48.781  INFO 4593 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-29 11:53:48.892  INFO 4593 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-04-29 11:53:48.893  INFO 4593 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1269 ms
2019-04-29 11:53:49.130  INFO 4593 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-29 11:53:49.375  INFO 4593 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-29 11:53:49.380  INFO 4593 --- [           main] io.minimal.Minimal                       : Started Minimal in 2.525 seconds (JVM running for 2.9)
2019-04-29 11:54:01.267  INFO 4593 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-04-29 11:54:01.267  INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-04-29 11:54:01.286  INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 19 ms
MINIMAL: INTERCEPTOR PREHANDLE CALLED
MINIMAL: GETMINIMAL()
MINIMAL: INTERCEPTOR POSTHANDLE CALLED
MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED

3
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Configuration
public class AuthenticationHandlerInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

        if (validrequest) {
         //fill data here add pass to next level
            return true;
        } else {
      // if you opt to not to proceed the request further you can simply return false here
            return false;
        }
    }

}

prehandle() – 在实际处理程序执行之前调用,但视图尚未生成

postHandle() – 在处理程序执行后调用

afterCompletion() – 在完成请求并生成视图后调用

"Original Answer" 翻译成 "最初的回答"

@Xenonite请看一下。 - RAJKUMAR NAGARETHINAM
1
这是最佳选择之一。 - TuGordoBello

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接