日期:2014-05-18  浏览次数:20766 次

表单提交中文至Servlet乱码
环境:NetBeans   +   JDK1.6

源代码:
index.jsp

<HTML>
<HEAD>
<TITLE> TEST </TITLE>
</HEAD>
<BODY>
<FORM   METHOD=GET   ACTION= "/Servlet/Hello ">
<INPUT   TYPE=TEXT   NAME= "name "   > <P>
<INPUT   TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

Hello.JAVA

import   java.io.*;
import   javax.servlet.*;
import   javax.servlet.http.*;

public   class   Hello   extends   HttpServlet   {
       
        public   void   doGet(HttpServletRequest   req,   HttpServletResponse   res)
        throws   ServletException,   IOException   {
               
                res.setContentType( "text/html;charset=UTF-8 ");
                res.setHeader( "Content-language ",   "zh ");
               
                PrintWriter   out   =   res.getWriter();
                //String   name   =   req.getParameter( "name ")

                String   name   =new   String(req.getParameter( "name ").getBytes( "iso-8859-1 "), "UTF-8 ");
               
                out.println( " <HTML> ");
                out.println( " <HEAD> <META   content=text/html;   charset=gb2312   http-equiv=Content-Type> </HEAD> ");
                out.println( " <BODY> ");
                out.println( "你好,   "   +   name);
                out.println( " </BODY> </HTML> ");
        }
       
        public   String   getServletInfo()   {
                return   "A   servlet   that   knows   the   name   of   the   person   to   whom   it 's "   +
                                "saying   hello ";
        }
}

也看了之前不少朋友关于乱码的文章,可是一直没有解决

上面的程序用POST方法则一点问题也没有,用GET方法就是乱码

我是个超级新手,基本上啥也不会,过滤器也不知道怎么加进去~~

还是NETBEANS5.5的傻瓜环境

请教~~



------解决方案--------------------
写一个filter,在其doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 方法中调用request.setCharacterEncoding( "GB2312 ");

package com.forecast.filter;