【解決URL路徑編碼亂碼】
@Test
public void test() throws Exception {
String text = "中國";
// 進行URL編碼操作
String encode = URLEncoder.encode(text, "utf-8");
System.out.println("編碼後的結果:" + encode);
// 進行URL解碼操作
String str = URLDecoder.decode(encode, "utf-8");
System.out.println("解碼後的結果:" + str);
}
【參數的亂碼問題】
編碼操作:
字符串 --> 編碼
byte[] data = str.getByte("utf-8");
解碼操作:
編碼 --> 字符串
String str = new String(data, "utf-8");
GET方式:
參數是在URL中的(請求行中)。
解決方案一:
// 獲取參數,默認是使用iso8859-1進行解碼(iso8859-1字符集支持中文嗎?不支持)
String name = request.getParameter("name");
// 解決GET方式中文參數的亂碼問題,注意:本方法只對GET方式有效
// 第二個參數(編碼)應根據情況設置爲GBK或UTF-8或其他.
// 具體的是指定瀏覽器傳參數時所用的編碼,就是瀏覽顯示的網頁所用的編碼。
// (網頁顯示的是什麼編碼,那麼傳參數就用什麼編碼)
name = new String(name.getBytes("iso8859-1"), "utf-8");
解決方案二:
// 在conf/server.xml中配置request.getParameter()的默認使用的編碼爲正確的編碼
<Connector
connectionTimeout="20000" port="8080"
protocol="HTTP/1.1" redirectPort="8443"
URIEncoding="utf-8"
/>
POST方式:
參數是在請求的實體內容中。
解決方案:
// 設置請求的實體內容編碼(默認是iso8859-1)
// 這樣POST方式提交的參數中的中文就不會有亂碼了
// 注意1:此方案只對POST方式的參數亂碼問題有效!
// 注意2:此代碼一定要放到所有的getParameter()調用之前纔有效
request.setCharacterEncoding("utf-8");
具體代碼:
package itcast.test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyParServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
byte[] bytes = name.getBytes("iso8859-1");
name = new String(bytes, "utf-8");
String sex = request.getParameter("sex");
sex = new String(sex.getBytes("iso8859-1"),"utf-8");
System.out.println("name="+name+" sex="+sex);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
System.out.println("name="+name+" sex="+sex);
}
}