需要文字编码转换
你可以在没有往数据库中添加之前在页面中print出来看看是不是乱码
试一试这个函数
public String getChinese(String str){
try{
String str1=str;
byte[] str2=str1.getBytes("ISO8859-1");
String temp=str2.toString();
return temp;
}
catch(Exception e)
{
}
return "Null";
}
Top
userName = request.getParameter("textfield");
String password = request.getParameter("textfield2");
String email = request.getParameter("select");
userName = new String(userName.getBytes("8859_1"),"gb2312");
password = new String(password.getBytes("8859_1"),"gb2312");
email = new String(email.getBytes("8859_1"),"gb2312");
<%@ page contentType="text/html;charset=GB2312" %>
request.setCharacterEncoding("GBK");
关于jsp 程序开发中的乱码问题
经过一天的探索,终于把乱码问题解决了,心里舒畅了不少。
现将解决办法总结一下,希望对大家有所帮助。
以下为我的一个页面中的部分编码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" import="java.lang.*" %>
<%@page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
%>
</body>
</html>
我所有的页面的编码统一都是UTF-8(请注意UTF-8的写法,一定要严格大小写)。
1:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
这句话是设定jsp 页面的编码,如果是在IDE(如eclipse 或者netbeans)文件的格式会自动保存为UTF-8 格式,如果你用的是文本编辑器的话它默认的是ANSI编码,你需要将文件另存为UTF-8 格式的。
2:<%@page contentType="text/html; charset=UTF-8"%>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
有了这两名声明,在本页面中的信息就一般不会出现乱码了。
3:表单提交过程中的乱码。
声明<%
request.setCharacterEncoding("UTF-8");
%>
由于request 默认的是ISO8859-1 编码,所以在处理表单提交的内容并插入数据库就会出现乱码,声明一下就不用再转换了。
4:数据库乱码:
安装数据库的时候,设置默认编码为UTF-8
创建表结构时声明:
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL,
`password` varchar(100) NOT NULL,
`studentid` varchar(50) NOT NULL,
`truename` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
声明DEFAULT CHARSET=utf8;(注意在数据中utf8 应该这样写)。
连接数据库时声明采用UTF-8 编码:
如我的连接mysql 数据库时
<%
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url="jdbc:mysql://localhost/demo?user=root&password=root&useUnicode=true&characterEncoding=UTF-8";
Connection conn=DriverManager.getConnection(url);
Statement stmt=conn.createStatement();
%>
useUnicode=true&characterEncoding=UTF-8,即声明采用UTF-8 编码。
总结:
原则上是所有的编码统一使用一个,数据为中的编码和jsp 页面上的编码写法不一样(UTF-8 与utf-8).
做到以上几点,乱码问题解决!