方式一: 使用传统的Spring提供的字符编码过滤器
项目名称:034-springboot-character-encoding-filter
在com.abc.springboot.servlet包在创建MyServlet
package com.abc.springboot.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* ClassName:MyServlet
* Package:com.abc.springboot.servlet
* Description:
*/
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().print("SpringBoot MyServlet 世界您好");
//设置浏览器代码
resp.setContentType("text/html;character=utf-8");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
在application.properties中设置spring.http.encoding.enabled=false
#关闭springboot的http字符编码支持
#只有关闭该选项后,spring字符编码过滤器CharacterEncodingFilter才会生效
spring.http.encoding.enabled=false
测试:spring.http.encoding.enabled=true,向浏览器响应中文
resp.getWriter().print("SpringBoot MyServlet 世界您好");
测试:spring.http.encoding.enabled=false,向浏览器响应中文
可以在servlet中添加response.setContextType(“text/html;charset=utf-8”)指定浏览器编码方式。
项目名称:035-springboot-character-encoding-properties
从 springboot 1.4.2 之后开始新增的一种字符编码设置
#设置请求响应的字符编码
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
配置完毕后,通过浏览器测试
1、未添加字符编码设置
2、已添加字符编码设置