写了一个JSP小程序,用JDBC把数据写入数据库,但是始终解决不了乱码问题,求大家帮助。代码贴出来
本人JSP页面的编码用的使UTF-8,在网页上显示正常。
本人JSP页面的编码用的使UTF-8,在网页上显示正常。
<%! String xuehao,name,gender,age,jiguan,yuanxi,url,user,pass; %>
<%! int xuehaoi, agei; %>
<%! Connection conn; %>
<%! ResultSet rs; %>
<%! PreparedStatement pstemt; %>
<%! String transForm(String str){
String newstr;
try{
newstr = new String(str.getBytes("iso8859-1"),"utf8");
} catch (Exception e) {
newstr = "编码转换发生了异常";
}
return newstr;
}%>
try{
if(request.getParameter("xuehao").trim()!=null && !"".equals(request.getParameter("xuehao").trim())){
xuehao = transForm(request.getParameter("xuehao").trim());
} else {
System.out.println("学号为空,跳转到错误页");
response.sendRedirect("err.jsp");
return;//这个return是跳出if语句的,下边的语句依然可达。假如在if外使用,就会使下边的代码不可达。
}
name = transForm(request.getParameter("name").trim());
gender = transForm(request.getParameter("gender").trim());
age = request.getParameter("age").trim();
jiguan = transForm(request.getParameter("jiguan").trim());
yuanxi = transForm(request.getParameter("yuanxi").trim());
} catch(Exception e){
System.out.println("没有拿到数据");
}
try{
DataBaseUtils dbu = new DataBaseUtils();
dbu.intiDatabase();
url = "jdbc:mysql://localhost:3306/stumager";
user = "root";
pass = "";
conn = dbu.getconn(url, user, pass);
pstemt = conn.prepareStatement("insert into stu value(?,?,?,?,?,?)");
pstemt.setInt(1, xuehaoi);
pstemt.setString(2, name);
pstemt.setString(3, gender);
pstemt.setInt(4, agei);
pstemt.setString(5, jiguan);
pstemt.setString(6, yuanxi);
pstemt.execute();
response.sendRedirect("list.jsp");
} catch(Exception e){
System.out.println("数据库异常");
response.sendRedirect("err.jsp");
}
按照网上的方法修改了Mysql的编码,查询结果也贴出来
MariaDB [stumager]> show variables like "%char%"; +--+--+ | Variable_name | Value | +--+--+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | character_sets_dir | C:\xampp\mysql\share\charsets\ | +--+--+
但是结果还是乱码,写到数据的时,数据已经成了乱码。求指导
解决方案
30
30
数据库乱码解决无非检查三个问题。1.JSP文件首行有没指定为UTF8,2.有没在web.xml中指定编码过滤器,3楼上的已经说了url = “jdbc:mysql://localhost:3306/stumager?characterEncoding=UTF-8″;