数据库乱码
这是写的一个简单的注册页面servlet
package servlet;
import
java.io.IOException;
import bean.DBConn;
import java.sql.*;
import
javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Register extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws
ServletException,
IOException {
this.doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DBConn db=new DBConn();
request.setCharacterEncoding("utf-8");
String uname=request.getParameter("uname");
String pwd=request.getParameter("pwd");
String username=request.getParameter("username");
String sex=request.getParameter("sex");
String isteacher=request.getParameter("isteacher");
String grade=request.getParameter("grade");
System.out.println(grade);
ResultSet rs=null;
PreparedStatement ps;
String sql="select * from userinfor where uname='"+uname+"'";
try{
rs=db.query(sql);
if(rs.next()){
request.setAttribute("msg","该用户名已存在");
request.getRequestDispatcher("register.jsp").forward(request, response);
}
else{
String sql2="insert into userinfor(uname,password,username,sex,isteacher,grade)values(?,?,?,?,?,?)";
ps=db.getPstmt(sql2);
ps.setString(1, uname);
ps.setString(2, pwd);
ps.setString(3, username);
ps.setString(4, sex);
ps.setString(5, isteacher);
ps.setString(6, grade);
ps.executeUpdate();
request.setAttribute("msg","注册成功");
request.getRequestDispatcher("register.jsp").forward(request, response);
}
}
catch(Exception e){
System.out.print("数据注册失败");
}
}
}
数据库操作bean
package bean;
import java.sql.*;
public class DBConn {
String driverName="com.mysql.jdbc.Driver";
String username="root";
String password="123";
String dbName="user";
String url="jdbc:mysql://localhost/"+dbName+"?characterEncoding=UTF-8";
Connection conn;
Statement stmt;
ResultSet rs=null;
PreparedStatement pstmt;
public DBConn(){
try{
Class.forName(driverName);
conn=DriverManager.getConnection(url,username,password);
}
catch(Exception e){
System.out.println("数据库
连接失败");
}
}
public PreparedStatement getPstmt(String sql)throws Exception{
pstmt=conn.prepareStatement(sql);
return pstmt;
}
public ResultSet query(String sql)throws Exception{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
return rs;
}
public int update(String sql)throws Exception{
int nn;
stmt=conn.createStatement();
nn=stmt.executeUpdate(sql);
return nn;
}
}
注册成功后页面信息显示都正常,但在mysql下中文显示都为“?”
编码哪里出错了
------解决方案--