Spring Boot RestController:拦截传入的请求

时间:2019-04-25 14:51:03

标签: spring request interceptor

我目前正在编写某种框架,该框架将允许其他人为其编写REST控制器。自然,我希望那些“其他”与我的代码中发生的事情尽可能少地互动。

具体来说,我希望并需要访问请求数据(即 RequestEntity,然后由其他控制器处理请求。在控制器处理请求之前先“拦截”请求,然后才让控制器处理请求。

考虑以下代码:

@RestController
@RequestMapping("/")
public class MyController {

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

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

现在我需要的是调用ExternalClass.doStuffWithRequestEntity(requestEntity);而不需要显式调用它。是否可以在某个类中调用某种方法(将RequestEntity传递给它!)而不必显式调用它?

此外,上述Interceptor类应创建并配置一个对象,然后该对象再次可供其余控制器使用。

我会在想类似的东西

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();
    }
}

之前被执行。

这个想法是,每个(!)传入请求都将被解析,并且其内容将被解码,而其余控制器的程序员完全不必关心这一点。他们应该只通过MyClass实例访问数据。

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:2)

Spring-boot允许我们配置自定义拦截器。通常,在Spring Boot应用程序中,所有内容都是自动配置的,在这种情况下,我们可以使用WebMvcConfigurerAdapter 自定义。只需扩展{ {1}},并提供此类中所需的配置。

请记住添加WebMvcConfigurerAdapter批注,以便在组件扫描期间spring可以拾取此类。

@Configuration

这是通常向Spring Boot应用程序添加拦截器的方式。希望这可能有助于回答您的问题。

从spring 5.xx或spring-boot 2起@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired HandlerInterceptor customInjectedInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(...) ... registry.addInterceptor(customInjectedInterceptor).addPathPatterns("/**"); } } 被标记为已弃用。WebMvcConfigurerAdapter接口(由抽象类{{1 }})从Spring 5开始,包含其所有方法的默认实现。结果,抽象适配器类被标记为已弃用。您可以按照以下方式采用它:

WebMvcConfigurer

答案 1 :(得分:1)

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 ()–在完整请求完成并生成视图之后调用

答案 2 :(得分:1)

对于所有在此处遇到相同或相似问题的人,这是一个带有Interceptor的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