一、 前台JSP页面传值,直接用servlet的request.getParameter()接收,若编码方式不一致,会产生乱码。
解决方式:重新编码。
例: 前台传参:
function do_search1(){
form1.action="../text?hy=所房琯改革改革";
form1.submit();
}
在servlet中接受:用request.getParameter()
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<%@ page contentType=/"text/html; charset=GBK/" %>");
out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST methodff的方法");
out.println(request.getParameter("hy"));//直接取,显示乱码
//out.println("告诉你的话:"+new String(request.getParameter("hy").getBytes("ISO8859_1"),"GBK"));
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
解决:s=request.getParameter("hy");
s1=new String(s.getBytes("ISO8859_1"),"GBK"));
s1就是你想要的值。
注意:后面的编码方式不一定是GBK,主要是要与前台传来字串的页面的编码方式一致。
二、中文在servlet中输出到新的页面时,若不指定编码方式会产生乱码。
例:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<%@ page contentType=/"text/html; charset=GBK/" %>");
out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST methodff的方法");
System.out.println(request.getParameter("hy"));
out.println("告诉你的话:"+new String(request.getParameter("hy").getBytes("ISO8859_1"),"GBK"));
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
直接输出,产生乱码,“告诉你的话:"等中文显示乱码
解决: response.setContentType("text/html;charset=GBK");
注意:编码不一定是GBK,要与前台对应。