servlet 关键代码 :
String queryField = request.getParameter("queryField").toString();
String queryText = request.getParameter("queryText").toString();
queryText = new String(queryText.getBytes("ISO-8859-1"), "UTF-8"); Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/mydb?characterEncoding=UTF8",
"root", "111");
PreparedStatement pStmt = conn
.prepareStatement("select * from t_books where "
+ queryField + " like ?");
pStmt.setString(1, "%" + queryText + "%"); ResultSet rs = pStmt.executeQuery(); List<String[]> result = new java.util.ArrayList<String[]>(); while (rs.next())
{
String[] row = new String[4];
row[0] = rs.getString("name");
row[1] = rs.getString("author");
row[2] = rs.getString("isbn");
row[3] = rs.getString("price");
result.add(row);
}
pStmt.close();
conn.close();

request.setAttribute("result", result);
RequestDispatcher rd = request
.getRequestDispatcher("/result.jsp");
rd.forward(request, response);
跳转的jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
<html>
<head> <title >查询结果</title>
</head>
<body> 
<table border="1">
<tr align="center">
<td>书名</td>
<td>作者</td>
<td>ISBN</td>
<td>价格</td>
</tr>
<c:forEach var="row" items="${result}">
<tr>
<td>${row[0]}</td>
<td>${row[1]}</td>
<td>${row[2]}</td>
<td>${row[3]}</td>
</tr>
</c:forEach>
</table>
</body>
</html>  
敲入  http://localhost:8080/demo/servlet/QueryBook?queryField=name&queryText=ajax
出现中文乱码

解决方案 »

  1.   


    request.setAttribute("result", result);之前加入request.setCharacterEncoding("utf-8") ;
      

  2.   

    我的数据库插入语句:
    INSERT INTO mydb.t_books (id, name, isbn, author, price) VALUES
    (1, '人月神话', '6787102165345', '布鲁克斯', 52),
    (2, 'Ajax基础教程', '5643489212407', '阿斯利森', 73),
    (3, 'Thinking in C++', '7111171152', 'Bruce Eckel', 66),
    (4, 'SQL Server 2005技术详解', '712489876532', '王超', 72),
    (5, 'Java网络基础', '765129876213', '赵宇', 61);
    是直接在mysql上执行的。
      

  3.   

    小弟不才,不知道怎么直接在数据表上填数据,以前只接触过sqlserver,net,现在做项目要用到javaee,坑爹啊
      

  4.   

    那你就把你的数据库编码都改成utf8  再执行插入语句数据库应该是不会有乱码了。试下看吧。
      

  5.   

    使用request.setCharacterEncoding("UTF-8")解决中文乱码
      

  6.   

    我装了一个Navicat Lite,打开里面的数据果然乱码,谢谢!