首先附上最刚开始的代码,功能是向数据库中插入数据,数据库中的属性如下:
<%
String action = request.getParameter("action"); //表单中提交过来的数据。
if(action != null && action.equals("submit")) { //如果进行提交,则进行数据插入
String title = request.getParameter("title");
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver"); //加载及注册jdbc驱动
String url = "jdbc:mysql://localhost:3306/bbs?user=root&password=199288";
Connection con = DriverManager.getConnection(url);
con.setAutoCommit(false); //设置不自动提交
String psql = "insert into article values (null, 0, ?, ?, ?, now(), 0)";
PreparedStatement pstmt = con.prepareStatement(psql, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt(1, -1);
pstmt.setString(2, title);
pstmt.setString(3, content);
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
int id = rs.getInt(1);
rs.close();
Statement stmt = con.createStatement();
String ssql = "update article set rootid =" + id + " where id =" + id;
stmt.executeUpdate(ssql);
con.commit(); //手动提交
con.setAutoCommit(true); //还原
if(stmt != null) {
stmt.close();
stmt = null;
}
if(pstmt != null) {
pstmt.close();
pstmt = null;
}
if(con != null) {
con.close();
con = null;
}
response.sendRedirect("index.jsp");
}
%>
运行时可以看到页面展示出来的中文出现乱码的情况,经过测试,该页面所得到的数据位为乱码,因此在首句插入以下代码:
request.setCharacterEncoding("utf-8");
然后中文显示就恢复正常了。
ps:有的情况下,尽管修改了页面的编码,但是还是显示乱码,这是应该测试以下数据库中是否乱码,或者从数据库中拿到的数据是否乱码,依次判断问题出在哪里。然后进行对应的修改。