小编典典

request.getParameter()在Java Servlet中无法正确显示字符编码

jsp

我在Java Servlet文件中使用UTF-8遇到了一些问题。当我在URL中获得参数值时,UTF-8字符出现了一些问题。它不能正确显示日语字符。

Jsp标头已经有

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

我将连接器中的URIEncoding设置添加到server.xml中的UTF-8。

<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

我在jsp中编写了以下代码。

<s:textfield key="txt_name" name="txt_name" id="txt_name"
maxlength="64"></s:textfield>

<a href="javascript:showModalWindow('PopUpFile!init.action?<%=Common.PASSWORD%>=<%=Common.encript(ID, Code)%>','',940,650);">
<s:property value="PopUp Link" />
</a>

<script>
    function showModalWindow(x_URL, x_ARG, x_WIDTH, x_HEIGHT) {
        var x_OPT = "dialogHeight: " + x_HEIGHT + "px; " + "dialogWidth: "
                + x_WIDTH + "px; "
                + "edge: Raised; center: Yes; resizable: Yes; status: Yes;";
        x_URL += "&name="+document.getElementById("txt_name").value;
        var retValue = window.showModalDialog(x_URL, x_ARG, x_OPT);
        if (retValue != null) {
            document.forms.frm.action = "ParentFile!getUser.action";
            document.forms.frm.submit();
        }
    }
</script>

然后,我在Java Servlet中编写了以下代码。

if(g_request.getParameter("name") != null){
    g_session.setAttribute(NAME, g_request.getParameter("name"));
}

我还用request.setCharacterEncoding()JavaServlet中的方法进行了测试,但它实际上并没有工作。尽管我从其他人的问题的答案中尝试了很多方法,这些问题中servlet中的字符编码有关,但是直到我解决问题为止。

如何正确显示字符编码?提前致谢。


阅读 567

收藏
2020-06-08

共1个答案

小编典典

ISO-8859-1默认情况下,大多数服务器(包括ApacheTomcat服务器)都配置为使用参数编码。我认为除非拥有私有专用服务器实例,否则您将不会更改此设置。因此,程序员的技术是手动编码/解码这些参数。由于您使用的是JavaScript,因此具有encodeURI()encodeURIComponent()内置函数。

x_URL += "&name="+encodeURI(document.getElementById("txt_name").value);

在Java中,请使用URLDecoder来解码参数。

java.net.URLDecoder.decode(((String[])request.getParameterMap().get("name"))[0], "UTF-8"));

注意,如果使用的是Struts2 dispatcher结果类型,则无需解码查询字符串中的参数。这些参数通过解析UrlHelper

但是,我不记得我在解码时会在Struts2中自动解码那些参数。

通常,您应该知道,如果您在URL中传递参数,则应该对它们进行URL编码。如果您提交表单,则无需这样做,因为表单是x-www-form- urlencoded,请参见17.13.4表单内容类型

2020-06-08