javaweb中解决中文乱码问题

有时候,乱码问题真的是很烦,你在前台写一些数据放到后台数据库的时候会出现乱码问题,再显示在前台的时候依然是乱码问题,有人说,把所有需要编码的地方都写上UTF-8就可以了,但是有时候你发现自己能改的地方都改了还是会出现乱码的问题,比如jsp页面上,数据库编码和表编码都没问题的情况下,还是会出现乱码问题,这其实问题是出在服务器上。好了,下面我们就来看看是如何一步一步解决乱码问题的吧。

 一、 JSP页面和浏览器:保证在jsp页面上的pageEncoding和contextType的charset编码一致,都支持中文(UTF8),还需要保证浏览器的显示的字符编码也和请求的jsp页面的编码一致:

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>

 二、 服务器编码问题:以tomcat为例,因为获取中文参数值,默认使用的是ISO-8859-1编码,就是说你在jsp定义一个text标签,输入中文,传到后台处理的时候编码方式是ISO-8859-1的,这里有三种解决途径:

1.对post请求:只要在获得参数之前使用 request.setCharactorEncoding("UTF-8");就没问题了。

  对于get请求:前面的方式对于get请求是不行的。还有加上这句话,修改useBodyEncodingForURI属性为true:我们可以通过对useBodyEncodingForUR来使得可以通过在Tomcat的config/server.xml上通过修改
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" useBodyEncodingForURI="true" />
 
2.万能的方法:String val = request.getParameter("username");
String username = new String(val.getBytes("iso-8859-1"),"UTF-8");但是这种方法比较麻烦,对每一个传进来的参数都要进行转码;
 
3.这种方法我没有完全的验证:只需要在config/server.xml上添加上这属性就不需要request.setCharactorEncoding("UTF-8");
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8" />
 
三、数据库方面:这里最多问题就在于MYSQL数据库的编码问题,还有就是创建数据库的编码问题和表的编码问题:这里我一般都是把需要设置编码的都设置成UTF-8就没有问题了,创建数据库和表的时候注意下就没有问题了,下面放下windows上的配置文件my.ini(mysql 5.6):
------------------------------------------------------------------------------------

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html
# *** DO NOT EDIT THIS FILE. It's a template which will be copied to the
# *** default location during install, and will be replaced if you
# *** upgrade to a newer version of MySQL.

[mysqld]

# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M

# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin

# These are commonly set, remove the # and set as required.
basedir = C:\Program Files\MySQL\MySQL Server 5.6
datadir = C:\Program Files\MySQL\MySQL Server 5.6\data
# port = .....
# server_id = .....
port = 3306
character-set-server=utf8
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

[client]
default-character-set=utf8
port = 3306
[mysql]
default-character-set=utf8

------------------------------------------------------------------

好了,先到这里了。
 
 
 
posted @ 2016-07-18 23:02  wen73  阅读(344)  评论(0编辑  收藏  举报