这个小例子中,我们已经:
- 整个项目在eclipse中指定采用UTF-8
- 在web.xml中对jsp的配置已经设置了<page-encoding>UTF-8</page-encoding>
- 在jsp文件中,已经给出了<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
但是我们仍碰倒在数据库中输入中文为??的乱码情况。跟踪过程发现,乱码在两个地方:
- 页面上输入中文,但是在controler中,将输入打出来出现乱码
- 解决上述问题后,发现在mysql的请求中,中文变成了??
这里谈谈我的解决方法。
解决从POST中获取正确获取中文UTF-8编码
设置了一个filter,将http的请求和响应转为utf-8编码。
@WebFilter(filterName = "/GlobalFilter",urlPatterns = "/*")
public class GlobalFilter implements Filter {
public GlobalFilter() {}
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//编码适配
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
httpRequest.setCharacterEncoding("UTF-8");
httpResponse.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {}
}
解决mysql语句中的中文编码
需要在jdbc url中加上characterEncoding=utf8。例如:
jdbc:mysql://192.168.2.52:3306/AdvancedMappings?useSSL=true&useUnicode=true&characterEncoding=utf8
如果我们使用tomcat的jdbc连接池,则在context.xml设置为:
<Resource name="jdbc/mariaTest" type="javax.sql.DataSource"
maxTotal="20" maxIdle="5" maxWaitMillis="10000"
username="test" password="123456"
driverClassName="com.mysql.cj.jdbc.Driver"
defaultTransactionIsolation="READ_COMMITTED"
url="jdbc:mysql://192.168.2.52:3306/AdvancedMappings?useSSL=true&useUnicode=true&characterEncoding=utf8" />
相关链接:我的Professional Java for Web Applications相关文章