使用gb2312乱码,utf-8正常

论坛 期权论坛 脚本     
已经匿名di用户   2022-4-13 16:43   2019   0

问题:使用gb2312编码会导致在终端输出和网页输出都是乱码,使用utf-8则不会。原因:jsp使用的编码方式是gb2312,这个编码方式决定了jsp页面所有显示文字的编码方式,包括text组件中输入的内容。对于get方法,请求参数是直接拼接在url后面的,而这个参数的编码应该也是由jsp使用的编码方式决定的。这些参数到达tomcat后,会首先经过一次解码,这个过程是程序不能干预的,发生在servlet所有的操作进行之前。而tomcat8之后默认的编码方式是utf-8,两个编码方式的不一致就导致了乱码。


对于get方法,request.setCharacterEncoding方法是不起任何作用的。

如果想让使用gb2312编码不出现中文乱码,就得去tomcat的配置文件中修改默认编码方式:

但是这种方法不建议使用。


如果既不想修改配置文件,还想使用gb2312编码,那么可以将请求的方法设为post,因为post提交的候数据是以表单的形式进行的,而不是直接拼接到url的后面,这就使得我们可以控制它使用的编码方式。

request.setCharacterEncoding方法是可以对post方法起作用的。

最推荐的方法:只要是上传参数中有中文,将要上传的参数string替换为

URLEncoder.encode("string","utf-8");

想要获取的参数中有中文,将要获取的参数string替换为

 URLDecoder.decode("string","utf-8");


对于下面的代码,如果使用utf-8编码,那么url后面跟的参数中文是正常显示的,而如果用gb2312,则参数中的中文也会乱码,但是后续获得参数不会乱码。

参考:https://blog.csdn.net/justloveyou_/article/details/55827718

https://blog.csdn.net/qq_35703954/article/details/74991972

https://blog.csdn.net/honghailiang888/article/details/50786963

<html>
<%@page pageEncoding="gb2312" %>
<body>
<h2>Hello World!</h2>
<%--<form action="RequestTest" enctype="multipart/form-data" method="get">

    <input type="submit" name="upload" value="上传"/>

</form>--%>

<form action="RequestTest" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit">
</form>
</body>
</html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet( "/RequestTest")
public class RequestTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //request.setCharacterEncoding("gb2312");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out=new PrintWriter(response.getWriter());
        out.println(username);
        out.close();

        System.out.println("====================");
        System.out.println(username+"\n"+password);
        response.sendRedirect("CheckCode");
    }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP