首頁  >  文章  >  Java  >  java幾種亂碼問題解決方法

java幾種亂碼問題解決方法

尚
原創
2019-12-21 15:53:482621瀏覽

java幾種亂碼問題解決方法

幾種java亂碼情況解決方法:

1、在Servlet中取得透過get方式傳遞到伺服器的資料時出現亂碼;

 public class RegistServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String name = req.getParameter("userName");
        byte[] bytes = name.getBytes("ISO8859-1");
        String newName = new String(bytes,"UTF-8");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}

解析:在doGet方法中定義一個name變數取得封裝在伺服器的客戶端資料userName,然後將name以「ISO8859-1」的方式賦值給位元組數組bytes,最後將此bytes數組以UTF-8的方式賦值給一個新建立的String變數newName,此時newName就是能正常顯示的數據,之所以這麼麻煩,是因為沒有直接的辦法一行程式碼解決,可以就當此方法為固定用法。

2、在Servlet中取得透過post方式傳遞到伺服器的資料時出現亂碼;

public class RegistServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //注意:post方式提交数据的乱码解决方式,放在getParameXXX方法之前
        req.setCharacterEncoding("UTF-8");
        //得到前台input框中name="username"和password="password"的value值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}

解析:post傳遞方式下解決亂碼問題很簡單,就req.setCharacterEncoding(“UTF -8”); 這一行程式碼,但需注意,要將這句話放在取得資料之前。

3、Servlet透過伺服器將資料回應到客戶端時出現亂碼;

public class RegistServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //方式一:
        resp.setContentType("text/html;charset=utf-8");
        //方式二:
        resp.setHeader("Content-type", "text/html");
        resp.setCharacterEncoding("UTF-8");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}

解析:注意,以上兩種方法在應用時要寫在輸出方法之前,另外,兩種方式效果一樣,因為方式一較簡潔,常用方式一。

4、HTML或JSP頁面在客戶端展示時出現的亂碼狀況。

<head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>form表单</title>
</head>

更多java知識請關注java基礎教學欄位。

以上是java幾種亂碼問題解決方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn