有没有办法在序列化之前拦截Spring MVC RestController端点的结果?

时间:2017-09-06 15:22:27

标签: java spring spring-mvc

My Spring RestController具有以下返回DTO的方法:

@RequestMapping(
        value = "/profile",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public UserProfileDto getUserProfile() {...}

我想拦截控制器方法调用,获取结果DTO并在序列化为JSON之前修改一些fied?

据我了解,有两种方法:

自定义过滤器:

不起作用,因为我只能获得序列化响应的字节流

Custom HandlerInterceptor:

但是我不知道我怎么能这样做,因为HandlerInterceptor中的postHandle有null ModelAndView,而AfterCompletion根本没有ModelAndView

1 个答案:

答案 0 :(得分:0)

您可以使用OncePerRequestFilter,如下例所示,

    @Component
    public class MyFilter extends OncePerRequestFilter {
      private final ObjectMapper objectMapper;

      @Autowired
      public MyFilter(final ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
      }

      @Override
      protected void doFilterInternal(
          final HttpServletRequest request,
          final HttpServletResponse response,
          final FilterChain filterChain) throws ServletException, IOException {

        // Add your code here ...

        }
        filterChain.doFilter(request, response);
      }
    }

您可以执行此操作来更改响应句柄

@RequestMapping(
        value = "/profile",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserProfileDto> getUserProfile() {
        return ResponseEntity.ok().body(new UserProfileDto());
}