JSP和Servlet傳值中文亂碼解決
阿新 • • 發佈:2019-01-08
1.JSP和Servlet傳值通過客戶端到伺服器會出現亂碼現象.
2.關於解決Servlet表單傳值Get和Post亂碼的解決.
2.1 doget的解決,先建一個工具類,便於呼叫轉碼成utf-8,靜態方法便於呼叫.
public class MyUTF { //封裝成工具類 public static String getNewString(String str) throws UnsupportedEncodingException { return new String(str.getBytes("ISO-8859-1"),"UTF-8"); } }
2.1.2 Servle裡的程式碼呼叫.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解決亂碼 response.setContentType("text/html;charset=utf-8"); //獲取介面的資料 使用封裝的方法 String name=MyUTF.getNewString(request.getParameter("name")); //定義輸出! PrintWriter out = response.getWriter(); out.println(name); out.println("你好,我是doGet!"); }
結果:
2.2 doPost的亂碼解決.
2.2.1 客戶端的post請求相對簡單,直接在Servlet裡新增轉換的程式碼.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解決中文亂碼 response.setContentType("text/html;charset=utf-8"); //請求解決亂碼 request.setCharacterEncoding("utf-8"); //響應解決亂碼 response.setCharacterEncoding("utf-8"); //輸出 PrintWriter out = response.getWriter(); String name=request.getParameter("name"); out.println(name); out.println("你好!我是doPost!"); }
結果: