San*_*Aye 7 java jsp servlets struts2 character-encoding
我在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" />
Run Code Online (Sandbox Code Playgroud)
我在连接器中将URIEncoding设置添加到server.xml中的UTF-8.
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
Run Code Online (Sandbox Code Playgroud)
我在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>
Run Code Online (Sandbox Code Playgroud)
然后,我在java servlet中编写了以下代码.
if(g_request.getParameter("name") != null){
g_session.setAttribute(NAME, g_request.getParameter("name"));
}
Run Code Online (Sandbox Code Playgroud)
我也用request.setCharacterEncoding()
java servlet中的方法进行了测试,但它并没有真正起作用.虽然我尝试了很多方法来解决其他人在stackoverflow中与servlet中的字符编码相关的问题,但直到我才能解决我的问题.
如何正确显示字符编码?提前致谢.
Rom*_*n C 12
大多数服务器(包括Apache Tomcat服务器)ISO-8859-1
默认配置为参数编码.我认为除非你有一个专用的专用服务器实例,否则你不会改变它.因此,程序员的技术是手动编码/解码这些参数.因为你使用JavaScript,还有的encodeURI()
或encodeURIComponent()
内置的功能.请参阅如何在JavaScript中编码URL.代码应该改变
x_URL += "&name="+encodeURI(document.getElementById("txt_name").value);
Run Code Online (Sandbox Code Playgroud)
在Java中使用URLDecoder
to decode参数返回.
java.net.URLDecoder.decode(((String[])request.getParameterMap().get("name"))[0], "UTF-8"));
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用的是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")
在读取参数之前运行.
归档时间: |
|
查看次数: |
35752 次 |
最近记录: |