需要进行设置的一共有三个地方,1.客户端 2.tomcat 3.server端
1.客户端请求部分需要设置编码格式,假设使用http程序自动请求数据,程序示例代码如下:
将请求数据使用URLEncoder进行UTF-8编码,然后使用wr将其写到请求的数据流中
private static InputStream httpRequest(String surl,Map attr) throws IOException{
String data = "";
InputStream is = null;
if (attr != null) {
Iterator it = attr.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode((String)attr.get(key), "UTF-8");
}
// Send data
URL url = new URL(surl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data.substring(1));
wr.flush();
is = conn.getInputStream();
}else{
URL url = new URL(surl);
URLConnection conn = url.openConnection();
conn.connect();
is = conn.getInputStream();
}
return is;
}
如果使用jsp则应当有如下内容:
<%@ page contentType="text/html; charset=UTF-8" %>
2.tomcat中需要设置一定connector
在server.xml中,确认设置了编码格式
<Connector URIEncoding="utf-8" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" port="80" redirectPort="8443">
</Connector>
3.服务器段程序需要设置编码格式,例如在servlet中,可以编写
public void service(ServletRequest request, ServletResponse resp)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
当然,服务器段一般会借助Filter来做这件事情,这样就不需要在每一个servlet中设置编码格式了,而且可以借助参数来确定使用什么样子的编码格式。