1、先将mysql-connector-java-5.1.6.jar数据库连接jar包放到../WEB-INF/lib/下;
<%@ page contentType="text/html; charset=utf-8" %> <%@ page import="java.sql.*" %> <html> <head> <title>学生列表</title> </head> <body> <%! Connection conn = null; ResultSet rs = null; String sqlStr = null; PreparedStatement pstmt = null; %> <table> <% try { String jdbcUrl = "jdbc:mysql://localhost:3306/drdb?useUnicode=true&charaterEncoding=utf8"; String userName = "root"; String password = "admin"; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(jdbcUrl, userName, password); sqlStr="select * from tb_student"; pstmt=conn.prepareStatement(sqlStr); rs=pstmt.executeQuery(); while (rs.next()) { %> <tr> <td><%=rs.getString("stu_id")%></td> <td><%= rs.getString("stu_name")%></td> <td><%=rs.getInt("stu_age")%></td> <td><%=rs.getString("stu_phone")%></td> <td><%= rs.getString("stu_sex")%></td> <td><%= rs.getString("stu_address")%></td> </tr> <% } rs.close(); pstmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } %> </table> </body> </html>
注:1、数据库字符集采用utf-8编码;
2、编辑文件保存时文件类型选择utf-8字符集
只有保持字符集的一致才能避免乱码的产生,在编写过程中若产生多次异常,则最好是重启一下tomcat服务器,因为有时问题可能并不在代码编写错误