在servlet用getOutputStream輸出中文問題
public class ResponseDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
test2(response);
}
private void test2(HttpServletResponse response) throws IOException,
UnsupportedEncodingException {
String data="中國2 ";
OutputStream out=response.getOutputStream();
out.write("<meta http-equiv='content-type'content='text/html;charset=UTF-8'>".getBytes());
out.write(data.getBytes("UTF-8"));
}
private void test1(HttpServletResponse response) throws IOException,
UnsupportedEncodingException {
String data="中國 ";
response.setHeader("Content-type", "text/html;charset=UTF-8");——控制瀏覽器用UTF-8來打開
OutputStream out=response.getOutputStream();
out.write(data.getBytes("UTF-8"));——用UTF-8輸出數據
}
下面寫錯了,瀏覽器會提示下載
private void test1(HttpServletResponse response) throws IOException,
UnsupportedEncodingException {
String data="中國 ";
response.setHeader("Content-type", "text/html,charset=UTF-8");——控制瀏覽器用UTF-8來打開
OutputStream out=response.getOutputStream();
out.write(data.getBytes("UTF-8"));——用UTF-8輸出數據
}
}
要是輸出數字5,一定要變成字符串,否則瀏覽器直接查表找5對應的字符去了