1. 程式人生 > >Servlet解決瀏覽器顯示中文亂碼

Servlet解決瀏覽器顯示中文亂碼

建立 test.java 程式碼:

@WebServlet("/test")
public class test extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("Sevlet設定中文顯示。");
	}
	
}

瀏覽器檢視:
在這裡插入圖片描述

在doGet方法中加入程式碼:

response.setContentType("text/html;charset=UTF-8");

test.java 程式碼如下:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("Sevlet設定中文顯示。");
	}

重啟Tomcat,瀏覽器檢視:
在這裡插入圖片描述