Response_案例2_输出字符数据与Response_案例3_输出字节数据
Response_案例2_输出字符数据
2. 服务器输出字符数据到浏览器
1.步骤:
1. 获取字符输出流
2. 输出数据
2.注意:
乱码问题:
1. PrintWriter pw = response.getWriter();获取的流的默认编码是ISO-8859-1
2. 设置该流的默认编码
3. 告诉浏览器响应体使用的编码
//简单的形式,设置编码,是在获取流之前设置
response.setContentType("text/html;charset=utf-8");
package qh.xueqiang.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/responseDemo04") public class ResponseDemo04 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取流对象之前,设置流默认编码:ISO-8859-1 设置为GBK //response.setCharacterEncoding("GBK"); //告诉浏览器,服务器发送的消息体数据的编码。建议浏览器使用该编码 //response.setHeader("content-type","text/html;charset=utf-8"); //简单的形式,设置编码 response.setContentType("text/html;charset=utf-8"); //1.获取字符串输出流 PrintWriter pw = response.getWriter(); //2.输出数据 // pw.write("<h1>nihaoya,nizaiganmayageigei~</h1>"); pw.write("<h1>你好呀,王耀我回来了~</h1>"); } }
Response_案例3_输出字节数据
3. 服务器输出字节数据到浏览器
步骤:
1. 获取字节输出流
2. 输出数据
package qh.xueqiang.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; @WebServlet("/responseDemo05") public class ResponseDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //简单的形式,设置编码 response.setContentType("text/html;charset=utf-8"); //1.获取字节输出流 ServletOutputStream os = response.getOutputStream(); //2.输出数据 os.write("萤火之光岂能与皓月争辉".getBytes()); } }