【问题标题】:request.getParamaterValues() not supporting UTF-8 while request.getParameter() doesrequest.getParamaterValues() 不支持 UTF-8 而 request.getParameter() 支持
【发布时间】:2014-11-17 16:31:02
【问题描述】:

HTML UTF-8 页面 (<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>) 正在使用具有单值和多值字段的表单。

使用request.getParameter(NAME) 发送特殊字符(例如ä ö ü)的单值字段可以正常工作。

但是,如果您使用多值字段并尝试通过request.getParameterValues(MULTI) 接收值,则无法正确解码特殊字符。

这是 servlet 规范中的错误,特别是 getParameterValues() 方法中的错误,还是我遗漏了什么?

我在 Tomcat 5 和 Java SE 6 上运行的 Web 应用程序中发现了这个问题。

【问题讨论】:

    标签: java servlets encoding utf-8


    【解决方案1】:

    与此同时,我得到了一个可行的解决方案(workaround)。但是,我仍然会对为什么直截了当的方法不起作用......

    工作解决方案:

    String[] strings = request.getParameterValues("multi");
    if (strings != null) {
        if (response.getCharacterEncoding().equals("ISO-8859-1")) {
            for (int i=0; i<strings.length; i++) {
                strings[i] = URLDecoder.decode(new String(strings[i].getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
            }
        }
        for (String s: strings) {
            // do whatever you want with correctly encoded special characters
        }
    }
    

    不起作用的代码(但应该?):

    String[] strings = request.getParameterValues("multi");
    if (strings != null) {
        for (String s: strings) {
            // special characters in variable s do not appear correctly
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-07
      • 2014-01-03
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多