servlet中 request.getParameter乱码的解决办法(表单使用get传递参数时)

    技术2025-07-19  4

    若是使用post则下文就没必要看了,直接使用HttpServletResponse的setContentType("text/html;charset=utf-8")方法即可解决乱码问题。

     

    在Tomcat服务器中,html页面使用表单(发送一个http请求给servlet进行对请求正文的处理,请求正文的默认字符编码是ISO-8859-1。

     

    参见Tomcat Wiki

    What is the default character encoding of the request or response body?

    If a character encoding is not specified, the Servlet specification requires that an encoding of ISO-8859-1 is used. The character encoding for the body of an HTTP message (request or response) is specified in the Content-Type header field. An example of such a header is Content-Type: text/html; charset=ISO-8859-1 which explicitly states that the default (ISO-8859-1) is being used.

     

    如果servlet需要处理中文字符,可以将请求正文的字符集转换为utf-8,如下所示:

     

    String user = new String(request.getParameter("user").getBytes("ISO8859-1"),"UTF-8");

    最新回复(0)