一、response.setContentType()
response.setContentType(MIME)的作用是使客户端浏览器,根据服务器传过来的MIME类型来对数据进行相应的处理最终以正确的形式展现给用户。
例如web浏览器就是通过MIME类型来判断文件是GIF图片。通过MIME类型来处理json字符串。Tomcat的安装目录\conf\web.xml 中就定义了大量MIME类型 ,可以参考。
response.setContentType("text/html; charset=utf-8");—— html
.setContentType("text/plain; charset=utf-8"); ——文本
text/javascript—— json数据
application/xml —— xml数据
二、response.setCharacterEncoding()
response.setCharacterEncoding()设置HTTP 响应的编码,如果之前使用response.setContentType设置了编码格式,则使用response.setCharacterEncoding指定的编码格式覆盖之前的设置.
response.setCharacterEncoding("utf-8");
response.setHeader("content-type", "text/html;charset=utf-8");
上面两句相当于下面这一句
response.setContentType("text/html;charset=utf-8");
三、注意事项
两个方法调用时必须在getWriter执行之前或者response被提交之前
本文介绍了如何使用response.setContentType()和response.setCharacterEncoding()方法正确设置HTTP响应的内容类型和字符编码,确保浏览器能正确解析并显示服务器发送的数据。
&spm=1001.2101.3001.5002&articleId=78127413&d=1&t=3&u=dc421f86bf7148249b8da74466980cfc)
19万+

被折叠的 条评论
为什么被折叠?



