java - 响应编码

标签 java spring spring-mvc model-view-controller

我收到的响应的标题为:

Content-Length:18588

Content-Type:application/json;charset=UTF-8

Date:Wed, 02 Dec 2015 12:58:51 GMT

Server:Apache-Coyote/1.1

是否有可能在将“application/json”编码字符串发送到 View 之前将其更改为“text/plain;charset=ISO-8859-1”编码?我正在使用 Spring MVC。 任何帮助将不胜感激。

最佳答案

您的要求是在将响应发送回客户端之前设置所需的内容类型,因此请使用httpServletResponse.setContentType("text/plain;charset=ISO-8859-1");

这是来自 javax.servlet.ServletResponse(setContentType(java.lang.String type) 的方法

以下摘录自文档。

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter has been called or after the response has been committed.

Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.

请注意:您应该在将响应提交回客户端之前使用此方法。从上面的摘录中可以看到这一点 - “如果在提交响应后调用此方法则无效。如果在调用 getWriter 或在提交响应后调用该方法,则它不会设置响应的字符编码。"


附注:

  • 为了使您的应用程序更具可扩展性,即将来支持更多语言的可能性,请使用“UTF-8”编码方案。
  • 请阅读我的 this answer深入了解为什么?

关于java - 响应编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34044084/

相关文章:

java - 如何在 Java 中使用 TimeZone 处理夏令时

jQuery Ajax文件上传: Required MultipartFile parameter 'file' is not present

java - 在 while 循环中将对象添加到列表

java - 如何创建读取制表符分隔文件的通用进程,并从中返回通用 Map

java - 从文件系统导入eclipse项目,然后在服务器上运行

java - 使用 SpEL 更新 Spring bean 属性的值

spring-mvc - set field+mappedBy 的不完整 setter

并行的Spring Boot多个缓存管理器

java - Spring bean注入(inject)错误: leads to a NullPointerException

java - 如何打开和显示多个文件夹中多个文件的内容?