您的位置:首页 > 编程语言 > Java开发

java 常见中文乱码问题解决

2016-11-07 00:00 197 查看
摘要: 在开发过程中,通常在jsp页面或是在解析各种文档类型的数据时产生乱码,其实防止乱码只要保证一点,就是编码格式一致就可以,下面具体举3种方法

关于中文乱码:

一、

1).在jsp页面上输入中文,要保证中文不乱码,有三个前提:

保证contentType=“text/html;charset=UTF-8”,pageEncoding=“UTF-8” charset和pageEncoding的编码一致,且都支持中文,通常建议取值为UTF-8,还需要摆正浏览器的显示的字符编码也和请求的jsp页面的编码一致。

2)、常见问题实例:(比如两个jsp,b.jsp获取a.jsp页面传过来的参数值,method为POST)

a.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>中文乱码</title>
</head>
<body>
<form action="hello.jsp" method="post">
userName:<input type="text" name="userName"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

b.jsp

<!--将请求的编码设置成UTF-8可以解决post的问题,但必须在获取请求参数之前设置编码 -->
<%
request.setCharacterEncoding("UTF-8");
%>
<%= request.getParameter("userName")%>

获取中文参数值:默认参数在传输过程中使用的编码为ISO-8859-1.

上面方法对get请求无效,在get请求得按下面方式解码转码:

<%
String val = request.getParameter("userName");
String userName = new String(val.getBytes("ISO-8859-1"),"UTF-8");
out.print(userName+"==");
%>

上面方式比较复杂,有种方式可以既适用于get请求又适用于post请求,修改tomcat参数,中文乱码是tomcat的 问题:

首先修改本地tomcat服务器/conf/server.xml中的:

<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" useBodyEncodingForURI="true"/>

<!-- 加一句useBodyEncodingForURI="true"-->


不要忘了在exclipse中也改一下tomcat的映射配置文件server.xml,useBodyEncodingForURI这个属性的意思是使用body里指定的字符编码,比URIEncoding要灵活一点,比如body已经指定了UTF-8,那么上面解码转码的方式还会是乱码,因为这个属性已经指定了字符集utf-8,解码也必须utf-8.

二、解析txt文档乱码。

windows下的文本文件字符集默认是GBK2312/GBK,在使用字符流或字节流读取文本文件的时候,文本文件可能是不同的字符集,比如有ANSI、GBK、UTF-8、Unicode等等,要想读入的数据不乱码,一点要保证读流传入的字符集和文本文件的字符集一致,这样不论文本文件的字符集是什么都可以防止乱码,所以要获取文本文件的字符集,比较专业一点的方法可以去找一下文件探测器,下面介绍一个比较实用的实例:

package com.hnasys.fft.web.component.file.analyze;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

import com.hnasys.fft.tool.land.Reflects;

public class TabFileAnalyzer {

public static String codeString(File fileName) throws Exception{
@SuppressWarnings("resource")
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
int p = (bin.read() << 8) + bin.read();
String code = null;
switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
case 0x5c75:
code = "ANSI|ASCII" ;
break ;
default:
code = "GBK";
}
return code;
}
public static <T> void analyze(File file, List<T> datas, Class<T> beanClass) {
BufferedReader br = null;
List<String> lines = new LinkedList<String>();
try {
try {
//读流时传入所读的文本文件的字符集,这样就可以保持传入的文本文件的字符编码可读入时候所用编码一致
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), codeString(file)));
} catch (Exception e) {
e.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
if (!line.trim().isEmpty()) {
lines.add(line + " ");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

for (String line : lines) {
T obj = null;
try {
obj = beanClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("创建对象失败", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("创建对象失败", e);
}
String[] lineCols = line.split("\t");
List<Field> fields = Reflects.getFields(beanClass);
for (Field field : fields) {
String value = lineCols[fields.indexOf(field)];
if (value == null)
continue;
value = value.trim();
if ("N/A".equals(value) || value.isEmpty())
continue;
// 实际类型字段值
Object rv = null;
// 设置到对象中
if (field.getType() == String.class)
rv = value;
else if (field.getType() == Integer.class)
rv = Integer.valueOf(value);
else if (field.getType() == Double.class)
rv = Double.valueOf(value);
else
throw new RuntimeException("暂不支持除String、Integer、Double以外的类型");
// 设置到字段中
field.setAccessible(true);
try {
field.set(obj, rv);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
datas.add(obj);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: