解決Servlet中GET請求參數爲中文時出現亂碼

服務器:Tomcat 7.0.xx
在Servlet的doGet方法中添加以下代碼:

String str = request.getParameter("username");
byte[] bytes = str.getBytes("iso-8859-1");
str = new String(bytes, "utf-8");

例子:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String str = request.getParameter("username");
        byte[] bytes = str.getBytes("iso-8859-1");
        str = new String(bytes, "utf-8");

        System.out.println(str);
    }


當服務器:Tomcat 8.0.xx時,不需要輸入 以上代碼,可以直接輸出

例子:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String str = request.getParameter("username");
        System.out.println(str);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章