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”);就没问题了。
String username = new String(val.getBytes(“iso-8859-1″),”UTF-8”);但是这种方法比较麻烦,对每一个传进来的参数都要进行转码;
# 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
——————————————————————