Spring的ResponseBodyAdvice:执行顺序?

时间:2015-02-14 02:54:38

标签: spring spring-mvc httpresponse spring-4

我想实现一个自定义ResponseBodyAdvice,它只查找Page<?>,然后将总元素数添加到响应标头中。

@ControllerAdvice
public class PageResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return Page.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ((Page<?>) body).getTotalElements();
        ...
    }

}

问题是:

  • 为什么body {在beforeBodyWrite方法中)属于MappingJacksonValue类型?

  • 有没有更好的方法来实现这一目标? /我使用了错误的拦截器吗?

我不想照顾包装器类,但我只想在Page方法中使用简单的未经修改的beforeBodyWrite对象。


编辑:

我现在只是extend AbstractMappingJacksonResponseBodyAdvice。这很有效,但不会感觉正确。也许有人还有更好的主意。

以下是Page -> Content-Range Header的代码:

@ControllerAdvice
public class PageResponseAdvice extends AbstractMappingJacksonResponseBodyAdvice {
    @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return super.supports(returnType, converterType) && Page.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
        Page<?> page = ((Page<?>) bodyContainer.getValue());
        Long from = null;
        Long to = null;
        if(page.getTotalElements() > 0 && page.getNumberOfElements() > 0) {
            from = Integer.valueOf(page.getNumber()).longValue()*page.getSize();
            to = from + page.getNumberOfElements() - 1;
        }
        response.getHeaders().add(
                HttpHeaders.CONTENT_RANGE,
                ContentRangeEncoder.encode(
                        "items",
                        from,
                        to,
                        page.getTotalElements()
                )
        );
        response.getHeaders().add(
                HttpHeaders.ACCEPT_RANGES,
                "items"
        );
    }
}

(如果有人有兴趣。这里是ContentRangeEncoder):

public class ContentRangeEncoder {
    private static final Pattern TYPE_PATTERN = Pattern.compile("[a-zA-Z0-9]+");
    private static final Predicate<String> TYPE_PATTERN_PREDICATE = TYPE_PATTERN.asPredicate();

    public static <T extends Number & Comparable<T>> String encode(String unit, T from, T to, T length) {
        StringBuilder sb = new StringBuilder();
        if(unit != null) {
            Assert.isTrue(TYPE_PATTERN_PREDICATE.test(unit));
            sb.append(unit).append(" ");
        }

        if(from == null && to == null) {
            sb.append("*");
        } else {
            Assert.notNull(from);
            Assert.notNull(to);
            Assert.isTrue(from.compareTo(to) <= 0);
            sb.append(from).append("-").append(to);
        }
        sb.append("/");
        if(length == null) {
            sb.append("*");
        } else {
            Assert.isTrue(to == null || length.compareTo(to) > 0);
            sb.append(length);
        }
        return sb.toString();
    }
}

1 个答案:

答案 0 :(得分:0)

至于为什么主体属于MappingJacksonValue类型,它取决于您的配置和您的特定处理程序方法的返回值。

作为旁注,WebMvcConfigurationSupportJsonViewResponseBodyAdvice添加到RequestMappingHandlerAdapter,如果在您之前调用此ResponseBodyAdvice bean,则可以解释为什么正文为{ {1}}。身体从一个{​​{1}}豆子传递到下一个,每个豆子以任何形式返回身体#34;它认为合适。

这是&#39; AbstractMappingJacksonResponseBodyAdvice&#39;的摘录,MappingJacksonValue的超类,看看身体会发生什么:

ResponseBodyAdvice