关于requst传递中文参数出现乱码问题的解法

版权声明:@渔闻520 https://blog.csdn.net/weixin_41060905/article/details/82556464

先看这样一个例子:

showinfo.jsp 用来显示获得的参数:

​
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>


姓名:<%=request.getParameter("name")%>
性别:<%= request.getParameter("rdo")%>

</body>
</html>

​

inputinfo.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018/9/9
  Time: 10:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="showinfo.jsp" method="post" name="frm">
    <font size="4">基本资料</font>
    <table width="700" cols="2" border="1">
        <tr>
            <td>姓名</td>
            <td><input type="text" name="name" required></td>
        </tr>
        <tr>
            <td>性别</td>
            <td><input type="radio" name="rdo" value="男" checked>男<input type="radio" name="rdo" value="女">女</td>
        </tr>
    </table>
    <input type="submit" value="注册" name="submit">
</form>
</body>
</html>

这样运行以后,会显示乱码。

解决方法:将showinfo.jsp修改为:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018/9/9
  Time: 10:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");//必须要写
%>
姓名:<%=request.getParameter("name")%>
性别:<%= request.getParameter("rdo")%>

</body>
</html>

或者将语句写为:

<%=new String(request.getParameter("name").getBytes("ISO-8859-1"),"utf-8”)%>

其意思为使用ISO-8859-1字符集将name的值解码为字节数组,再将这个字节数组按本页面page指令中设置的字符集utf-8来重新构造字符串。

这是因为,Tomcat默认用的是ISO-8859-1编码,不管页面用的是什么编码,Tomcat最后都会将其变成IOS-8859-1编码,当在另个页面用utf-8翻译的时候,就会将IOS-8859-1字符集翻译成utf-8字符集,就会发生错误乱码。在这种情况下,就要先将字符集用ISO-8859-1进行翻译,得到一个在ISO-8859-1下的字节数组,而后再用页面中采用的字符集将这个数组重构成一个字符串。

猜你喜欢

转载自blog.csdn.net/weixin_41060905/article/details/82556464