2019独角兽企业重金招聘Python工程师标准>>>
方案1:
页面端:
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
http://www.w3.org/TR/html4/loose.dtd">
Ajax:
function veryfy(){
//乱码问题解决:
//1.页面端发送的数据采用encodeURI,encodeURI($("#username").val()),服务器端采用new String(str.getBytes("iso8859-1","utf-8"));
//2.页面端发送的数据采用两次encodeURI,encodeURI(encodeURI($("#username").val())),服务器端URLDecoder.decode(str,"utf-8");
$.get("AjaxSeverlet?name=" + encodeURI($("#username").val()), null, function(data){
$("#msg").html(data);
});
}
服务器端:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
response.setHeader("charset","gb2312"); //设置返回页面的头 meta 信息
response.setContentType("text/html;charset=gb2312"); //设置输出的文档类型
// 以上内容在PrintWriter 声明前设置,杜绝乱码
PrintWriter out=response.getWriter();
//接收参数实例:(Ajax页面端到服务器端)
String s = request.getParameter("name");
s = new String(s.getBytes("iso-8859-1"), "utf-8");
System.out.println(s);
//服务器端到页面端:
// out.print("Ajax乱码解决"); //直接输出中文
/*
*从数据库中取中文数据
*/
SqlTools st = new SqlTools();
ResultSet rs = st.getResultSet("select seller from orders where orderid = 1");
String dbs = "";
try {
if(rs.next()) {
dbs = rs.getString("seller");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print(dbs);
}
方案二:
方案一有时候确实不稳定,只需要在页面端两次encodeURI,然后在服务器端用URI.decode() 解码