request.getParameter()在java servlet中没有正确显示字符编码

我在java servlet文件中遇到UTF-8的问题。 当我在URL中获取参数值时,我遇到了UTF-8字符的问题。 它无法正确显示日文字符。

Jsp头已经有了

  

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

  

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

  <a href="javascript:showModalWindow('PopUpFile!init.action?=','',940,650);">    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(); } }  

然后,我在java servlet中编写了以下代码。

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

我还测试了java servlet中的request.setCharacterEncoding()方法,但它确实不起作用。 虽然我尝试了很多方法来回答其他人在stackoverflow中与servlet中的字符编码相关的问题,但直到我解决问题我才能解决。

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

大多数服务器(包括Apache Tomcat服务器)默认配置为使用ISO-8859-1进行参数编码。 除非你有一个专用的专用服务器实例,否则我认为你不会改变它。 因此,程序员的技术是手动编码/解码这些参数。 因为你使用的是javascript,所以有encodeURI()encodeURIComponent()内置函数。 请参见如何在JavaScript中对URL进行编码 。 代码应该改变

 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表单内容类型 。

您是否使用System.out.println测试输出? 如果是这样,可能是它没有配置为UTF-8。

请参阅: 无法从JSP向Servlet发送特殊字符(UTF-8):显示问号

还要确保在读取参数之前运行request.setCharacterEncoding("UTF-8")

我有类似的错误并解决它使用Servletfilter如果您使用Spring,只需将此定义添加到web.xml

   encodingFilter org.springframework.web.filter.CharacterEncodingFilter  encoding UTF-8   forceEncoding true    encodingFilter /*  

如果你没有使用Spring编写一个servletfilter,如:

 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //Set character encoding as UTF-8 request.setCharacterEncoding("UTF-8"); filterChain.doFilter(request, response); } 

我想将f.khantsis的评论转发给答案,因为事实certificate这对我来说很重要。

重要提示:确保首先执行此filter,然后再执行其他filter,否则将无效。

我们的servletfilter中有一个正确的编码设置:

  request.setCharacterEncoding("UTF-8"); 

但是当我在request.getParameter放置一个断点时,它表明我们在设置编码之前读取参数。 它发生在另一个filter(csrf)中。 此时编码被冻结并进一步设置无效。 这可能与服务器有关,但在我们的情况下(Websphere)就是这种情况。