1. 程式人生 > >servlet 頁面中文亂碼

servlet 頁面中文亂碼

頁面: 

程式碼:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>使用者登入<h1>");
        out.println("<form action=\"\" method=\"\">");
        out.println("<p>使用者名稱:<input type=\"text\" name=\"name\" /></p>");
        out.println("<p>密碼:<input type=\"password\" name=\"pwd\" /></p>");
        out.println("<p><input type=\"submit\" value=\"登入\" /></p>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

修改後:

頁面:

程式碼:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 這一行一定要在 getWriter() 前面
        resp.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();
        out.println("<html>");
        
        // 加上這一行
        out.println("<meta http-equiv=\"content-type\" content=\"text/html\" charset=\"utf-8\"/> ");


        out.println("<body>");
        out.println("<h1>使用者登入<h1>");
        out.println("<form action=\"\" method=\"\">");
        out.println("<p>使用者名稱:<input type=\"text\" name=\"name\" /></p>");
        out.println("<p>密碼:<input type=\"password\" name=\"pwd\" /></p>");
        out.println("<p><input type=\"submit\" value=\"登入\" /></p>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }