servlet中中文乱码问题的解决

一、 前台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,要与前台对应。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值