【问题标题】:request.getParameter() fails on correctly encoded URLrequest.getParameter() 在正确编码的 URL 上失败
【发布时间】:2025-09-19 04:15:01
【问题描述】:

当我在 GWT 的 HttpServletRequest 中调用 request.getParameter( "filename" ) 时遇到了问题。这是我如何编码 URL 的代码:

String sFile = URL.encodeQueryString( "°^!§$%()=`´' glassfish +~#'@€-_²³.pdf" );
String sURL = GWT.getModuleBaseURL() + "filehttpservice" // name of the httpservlet
    + "?filename=" + sFile; // the name of the file to download
Window.open( sURL, "_blank", sFeatures ); // sFeatures are some window-settings

所以我想下载一个名称中包含一些特殊字符的文件。 URL 编码的名称是:

%C2%B0%5E!%C2%A7%24%25()%3D%60%C2%B4'%20glassfish%20%2B~%23'%40%E2%82%AC-_%C2%B2%C2%B3.pdf

这是正确的,因为我可以用这个名字直接在浏览器中调用文件。

因此,当请求到达 HttpServlet 的 get-Method 时,我想使用以下代码从其参数中提取文件名:

request.setCharacterEncoding( "UTF-8" );
String sFilename = request.getParameter( "filename" );

但是收到的文件名是:

°^!§$%()=`´' glassfish +~#'@â¬-_²³.pdf

这是完全错误的。

我已经搜索了很长时间并尝试了多种解决方案,但没有任何改变。有人知道我怎样才能收到正确的文件名吗?

【问题讨论】:

    标签: http servlets gwt


    【解决方案1】:

    request.setCharacterEncoding( "UTF-8" );doGet() 没有影响。在doGet() 中,queryString 在到达doGet() 之前被容器解析。

    您应该使用doPostrequest.getInputStream() 并自己解析queryString。并且不要在request.getInputStream() 之前使用request.getParameter(),否则它将不起作用。

    编辑 默认情况下,Java 将 String 编码为 utf-16 .. 所以您必须将其转换为 utf-8

    response.setHeader( "Content-Disposition", new String("attachment; filename=\"" + sUrlFilename + ".pdf" + "\"".getBytes("utf-8"),"ISO-8859-1") );

    【讨论】:

    • 好的,但如果我使用doPost,无论如何解码都会失败。我得到完全相同的错误文件名。好像和CharacterEncoding没有关系
    • @N43 ` URLDecoder .decode(new String(request.getParameter("filename").getBytes("iso-8859-1")), CHARSET_FOR_URL_ENCODING);`你可以在这里阅读更多@987654321 @
    • 谢谢!现在我自己正确解码参数,但响应面临另一个问题:当我设置 response-Header response.setHeader( "Content-Disposition", "attachment; filename=\"" + sUrlFilename + ".pdf" + "\"" ); 其中 sUrlFilename 是正确的 UTF-8-Filename 时:°^!§$%()=´' glassfish +~#'@€-_²³ 并且 ContentType 是 application/pdf; charset=UTF-8 Filename in下载提示显示^! $%()= ' glassfish +~#'@ -_ .pdf,这也是不正确的。你知道如何解决这个问题吗? (哦,response.setCharacterEncoding("UTF-8") 也被调用了)
    • @N43 您正在连接 utf-8utf-16 字符串.. Java 默认将 String 编码为 utf-16 .. 所以您需要将整个字符串转换为 utf-8 。我已经更新了我的答案。
    • 由于某些原因,UTF-8 中的字节编码对我不起作用。我使用MimeUtility.encodeWord( sUrlFilename, "ISO-8859-1", "Q" ); 解决了它。不过,非常感谢!让我开心:)
    【解决方案2】:

    正如 Anurag Anand 所说,这是一个编码问题;您必须配置您的 servlet 容器以将 URL 解码为 UTF-8。

    以 Tomcat 为例,这是在 Connector 级别使用 URIEncoding 属性配置的。使用 Jetty,可以使用 org.eclipse.jetty.util.UrlEncoding.charset 系统属性进行设置。

    【讨论】: