Response案例2_输出字符数据、Response案例3_输出字节数据
Response案例2_输出字符数据
步骤:
获取字符输出流
输出数据
@WebServlet( value = "/Servlet3")
public class Servlet3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取字符流输出流
PrintWriter re = response.getWriter();
// 输出数据
re.write("<h1>hello respose</h1>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
注意:
乱码问题
PrintWriter pw =response.getWriter();获取的流默认编码是ISO-8859-1
设置改流的默认编码
告诉浏览器响应体使用编码
简单的形式:
response.setContentType("text/html;charset = uft-8")
Response案例3_输出字节数据
服务器输出字节数据到浏览器
步骤:
获取字符输出流
输出数据
@WebServlet(value = "/ServletZijie")
public class ServletZijie 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 {
// 获取字节
ServletOutputStream stream = response.getOutputStream();
// 输出数据
stream.write("你好".getBytes("utf-8"));
}
}