如何在Spring控制器中返回纯文本?

2024-03-24

我想返回一个简单的纯文本字符串,如下所示:

@RestController 
@RequestMapping("/test")
public class TestController {
    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/my", method = RequestMethod.GET, produces="text/plain")
    public String test() {
        return "OK";
    }

问题:我还有一个全局 ContentNegotiation 过滤器,如下所示:

@Configuration
public class ContentNegotiationAdapter extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false)
                .favorParameter(true)
                .ignoreAcceptHeader(true)
                .useJaf(false)
                .defaultContentType(MediaType.APPLICATION_XML);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
    }
}

结果:每当我访问弹簧控制器时,我都会收到错误:

Could not find acceptable representation

问题:即使在内容协商中仅配置了 XML(我必须保留),如何强制控制器返回纯文本?


如果您删除produces="text/plain"从映射中,它返回纯文本,但标题设置为"application/xml"。这可能是不可取的。 我使用最新版本的 Spring Boot 进行了测试。

如果您使用的Spring版本>=4.1.2,可以尝试使用defaultContentTypeStrategy代替defaultContentType,在标头中设置正确的内容类型:

   configurer.favorPathExtension(false)
            .favorParameter(true)
            .ignoreAcceptHeader(true)
            .useJaf(false)
            .defaultContentTypeStrategy(new ContentNegotiationStrategy() {
                @Override
                public List<MediaType> resolveMediaTypes(NativeWebRequest nativeWebRequest) throws
                        HttpMediaTypeNotAcceptableException {
                    System.out.println("Description:"+nativeWebRequest.getDescription(false));
                    if (nativeWebRequest.getDescription(false).endsWith("/test/my")) {
                        return Collections.singletonList(MediaType.TEXT_PLAIN);
                    }
                    else {
                        return Collections.singletonList(MediaType.APPLICATION_XML);
                    }
                }
            })
            //.defaultContentType(MediaType.APPLICATION_XML)
;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Spring控制器中返回纯文本? 的相关文章

随机推荐