Java spring 框架 - 如何设置内容类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2605976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:47:48  来源:igfitidea点击:

Java spring framework - how to set content type?

javaspringspring-mvc

提问by Ian morgan

I have a spring action that I am rendering some json from the controller, at the minute its returning the content type 'text/plain;charset=ISO-8859-1'.

我有一个弹簧动作,我正在从控制器渲染一些 json,在它返回内容类型“text/plain;charset=ISO-8859-1”的那一刻。

How can I change this to be 'application/json'?

如何将其更改为“应用程序/json”?

采纳答案by Bozho

Pass the HttpServletResponseto your action method and set the content type there:

将 传递HttpServletResponse给您的操作方法并在那里设置内容类型:

public String yourAction(HttpServletResponse response) {
    response.setContentType("application/json");
}

回答by Ichiro Furusato

Yes, but this only works if one is grabbing the HttpServletResponse in the controller.

是的,但这只适用于在控制器中抓取 HttpServletResponse 的情况。

In Spring 3 we're being encouraged to avoid references to anything in the servlet domain, keeping things solely to our POJOs and annotations. Is there a way to do this without referencing the HttpServletResponse? I.e., keeping ourselves pure?

在 Spring 3 中,我们被鼓励避免引用 servlet 域中的任何内容,只保留我们的 POJO 和注释。有没有办法在不引用 HttpServletResponse 的情况下做到这一点?即,保持自己的纯洁

回答by Thomas Vanstals

Did you try using the MappingHymansonJsonView?

您是否尝试使用MappingHymansonJsonView

Spring-MVC View that renders JSON content by serializing the model for the current request using Hymanson's ObjectMapper.

Spring-MVC 视图,通过使用 Hymanson 的 ObjectMapper 序列化当前请求的模型来呈现 JSON 内容。

It sets the content-type to: application/json.

它将内容类型设置为:application/json

回答by JOKe

 @RequestMapping(value = "jsonDemoDude", method = RequestMethod.GET)
    public void getCssForElasticSearchConfiguration(HttpServletResponse response) throws IOException {        
        String jsonContent= ...;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response);
        wrapper.setContentType("application/json;charset=UTF-8");
        wrapper.setHeader("Content-length", "" + jsonContent.getBytes().length);
        response.getWriter().print(jsonContent);
}

You can also add the aditional X bytes or whatever for "callback" part in case you want JSONP( cross site json request ) .

您还可以为“回调”部分添加额外的 X 字节或任何内容,以防您需要JSONP(跨站点 json 请求)。