Request物件接收表單請求引數的中文亂碼處理
阿新 • • 發佈:2018-12-18
在開發中,很多人會遇到使用Request物件接收表單請求引數會遇到中文亂碼,至於怎麼處理呢?只需要瞭解其產生亂碼的原因,處理起來還是很容易的,接下來用程式碼演示:
* Request接收中文資料 */ public class RequestDemo3 extends HttpServlet { private static final long serialVersionUID = 1L; /** * 演示get方式處理中文亂碼 */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get接收資料:(開發中不常用) /** * get方式產生亂碼的原因: * * get方式提交的資料在請求行的url後面,在位址列上其實就已經進行了一次編碼了 * * 解決方案: * * 將存入到request緩衝區中的值以ISO-8859-1的方式獲取到,以UTF-8的方式進行解碼 */ String name = request.getParameter("name"); // 方式一: String encode = URLEncoder.encode(name, "ISO-8859-1"); String decode = URLDecoder.decode(encode, "UTF-8"); System.out.println("姓名:"+decode); // 方式二:(開發中常用) String value = new String(name.getBytes("ISO-8859-1"),"UTF-8"); System.out.println("姓名:"+value); } /** * 演示post方式處理中文亂碼 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // post接收資料:(開發中常用) /** * 產生亂碼的原因: * * post方式提交的資料是在請求體中,request物件接收到資料之後,放入request快取區中.緩衝區中就有編碼(預設ISO-8859-1:不支援中文) * * 解決方案: * * 將request的緩衝區的編碼修改即可. */ // 設定緩衝區的編碼 request.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); System.out.println("姓名:"+name); } }