群里一个小盆友写了两个jsp,通过jsp:forward传参时总是乱码,而页面、tomcat的编码都有设置,我一时激动就找了找解决办法

    两个JSP分别如下:

    • test1.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title<title>
    <head>
    <body>
    <jsp:forward page="test2.jsp" >
        <jsp:param name="name" value="你好"/>
        <jsp:param name="age" value="111"/>
    <jsp:forward>
    <body>
    <html>
    • test2.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <%
            String userName=request.getParameter("name");
            String age=request.getParameter("age");
        %>
        <title>Title</title>
    </head>
    <body>
    <%=userName%>
    <%=age%>
    test
    上略当分阃
    </body>
    </html>

    在test2中,使用new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
    没用,猜测是传输时的问题,于是google了以下jsp:forward传参乱码,看到解决办法是在test1.jsp种加上:

    <% request.setCharacterEncoding("utf-8");%>

    bingo!
    ps. 事后被小盆友膜拜了一下,然而其实我感觉挺汗颜的个破问题找了十几分钟 :joy: