【Servlet】Response的OutputStream与Writer输出数据乱码
的问题
OutputStream输出中⽂数据乱码问题解决⽅式:
package cn.lsh.servlet;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Response的OutputStream输出中⽂数据问题
public class Response extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//指定以UTF-8编码,那么就要指定浏览器以UTF-8解码,总之,编码与解码要相同,否者就会出现乱码。
//注意:第⼆个参数中间不要写成“,”否则当访问Servlet时会出现提⽰下载的情况。
response.setHeader("content-type", "text/html;charset=utf-8");
String str = "中国,我爱你";
OutputStream out = OutputStream();
out.Bytes("utf-8"));//指定以UTF-8编码。
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Writer输出数据乱码的问题解决⽅法:
以下是没有指定浏览以UTF-8码表打开所以导致浏览器输出乱码:
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/
/Response的OutputStream输出中⽂数据问题
public class Response extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//指定以UTF-8编码,那么就要指定浏览器以UTF-8解码,总之,编码与解码要相同,否者就会出现乱码。 //注意:第⼆个参数中间不要写成“,”否则当访问Servlet时会出现提⽰下载的情况。
//设置response使⽤utf-8码表,以控制response以什么码表向浏览器写出数据
response.setCharacterEncoding("UTF-8");
/*
//指定浏览器以什么码表打开服务器发送的数据
output的反义词response.setContentType("text/html;charset=utf-8");
*/
String str = "中国,我爱你";
PrintWriter pw = Writer();
pw.write(str);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
浏览器输出结果为:
以下指定浏览以UTF-8码表打开所以浏览器输出中⽂数据正常:
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Response的OutputStream输出中⽂数据问题
public class Response extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//指定以UTF-8编码,那么就要指定浏览器以UTF-8解码,总之,编码与解码要相同,否者就会出现乱码。 //注意:第⼆个参数中间不要写成“,”否则当访问Servlet时会出现提⽰下载的情况。
//设置response使⽤utf-8码表,以控制response以什么码表向浏览器写出数据
response.setCharacterEncoding("UTF-8");
//指定浏览器以什么码表打开服务器发送的数据
response.setContentType("text/html;charset=utf-8");
String str = "中国,我爱你";
PrintWriter pw = Writer();
pw.write(str);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
输出结果正常:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论