gpt4 book ai didi

java - 如何在 Spring MVC REST 中为 JSON 设置内容长度?

转载 作者:IT老高 更新时间:2023-10-28 13:57:05 26 4
gpt4 key购买 nike

我有一些代码:

@RequestMapping(value = "/products/get", method = RequestMethod.GET)
public @ResponseBody List<Product> getProducts(@RequestParam(required = true, value = "category_id") Long categoryId) {
// some code here
return new ArrayList<>();
}

如何配置 Spring MVC(或 MappingJackson2HttpMessageConverter.class)以默认设置正确的 header Content-Length?因为现在我的响应头 content-length 等于-1。

最佳答案

您可以将 ShallowEtagHeaderFilter 添加到过滤器链中。以下代码段对我有用。

import java.util.Arrays;

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

@Configuration
public class FilterConfig {

@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterBean = new FilterRegistrationBean();
filterBean.setFilter(new ShallowEtagHeaderFilter());
filterBean.setUrlPatterns(Arrays.asList("*"));
return filterBean;
}

}

响应正文如下所示:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
X-Application-Context: application:sxp:8090
ETag: "05e7d49208ba5db71c04d5c926f91f382"
Content-Type: application/json;charset=UTF-8
Content-Length: 232
Date: Wed, 16 Dec 2015 06:53:09 GMT

关于java - 如何在 Spring MVC REST 中为 JSON 设置内容长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24156490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com