如何更改 Spring @RestController 的响应内容类型标头

问题描述 投票:0回答:1

我正在尝试从过滤器类更改 HttpServletResponse 内容类型,但更改没有反映。

过滤器类别:

@Component
@Order(1)
public class TestFilter implements javax.servlet.Filter {
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        if (arg1 instanceof HttpServletResponse) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) arg1;
            httpServletResponse.setContentType("application/xml");
            arg1.setContentType("application/xml");
            
            String contentType = httpServletResponse.getContentType();  
            System.out.println("contentType : "+contentType);
            
        arg2.doFilter(arg0, new HttpServletResponseWrapper(httpServletResponse) {
            @Override
            public void setContentType(final String type) {
                
            }
        });
        String contentType1 = httpServletResponse.getContentType();
        System.out.println("contentType1 : "+contentType1);
        String contentType2 = httpServletResponse.getContentType();
        System.out.println("contentType2 : "+contentType2);
    }
    }
}

控制器:

@RestController
public class TestController {
    
    @PostMapping(path="/test", consumes = MediaType.ALL_VALUE,  
            produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
    public String test() {
        return "<SUCCESS></SUCCESS>";
    }
}

但我仍然得到 application/json 作为响应内容类型,它应该是 application/xml。我该如何解决这个问题?

响应日志: 内容类型:应用程序/xml contentType1:应用程序/json contentType2:应用程序/json

spring content-type spring-restcontroller
1个回答
0
投票
public ResponseEntity<?> test() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_XML);
    return new ResponseEntity<>("<SUCCESS></SUCCESS>", headers, HttpStatus.OK);
}
© www.soinside.com 2019 - 2024. All rights reserved.