The fundamental reason why java outputs Chinese garbled characters to HTML is the problem of inconsistent encoding, so the solution is to set the encoding method.
Among them, it is also divided into byte stream and character stream solutions.
Byte stream:
response.setHeader("Content-Type", "text/html;charset=UTF-8"); response.getOutputStream().write("我是字节流".getBytes("UTF-8"));
Character stream:
response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("我是字节流");
response output data Details:
(1) The two methods getOutputStream and getWriter are mutually exclusive. After calling any one of the methods, you cannot call the other method.
(2) The data written by the Servlet program to the ServletOutputStream or PrintWriter object will be obtained from the response by the Servlet engine. The Servlet engine will treat these data as the body of the response message, and then combine them with the response status line and each The response headers are combined and output to the client.
(3) After Serlvet's service method ends, the Servlet engine will check whether the output stream object returned by the getWriter or getOutputStream method has called the close method. If not, the Servlet engine tomcat will call the close method to close the output stream. object.
For more java knowledge, please pay attention to the java basic tutorial column.
The above is the detailed content of Solution to java output Chinese garbled characters to html. For more information, please follow other related articles on the PHP Chinese website!