一、向客户端写入数据

1、写入文字

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");//设置服务器的编码,默认是ISO-8859-1
response.setContentType("text/html; charset = utf-8");//告诉浏览器服务器的编码格式
response.getWriter().write("你好,JAVA");
}

response向客户端写入数据-LMLPHP

2、图片

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream out=response.getOutputStream();
File file=new File("图片路径");
FileInputStream fi = new FileInputStream(file);
byte[] buf = new byte[];
int len = ;
while ((len = fi.read(buf)) != -) {
out.write(buf, , len); // 将数组中的指定长度的数据写入到输出流中。
}
fi.close();
out.close();
}

采用了缓冲数组读入图片数据,减少了时间的消耗。创建ServletOutputStream对象,将数据输出到了客户端。

response向客户端写入数据-LMLPHP

二、response对响应的设置

1、response对象设置响应行状态码:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setStatus(404);
}

response向客户端写入数据-LMLPHP

2、response对象添加响应头:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Date date=new Date(121344444);
response.addHeader("zzz","I love JAVA.");
response.addIntHeader("myself",22);
response.addDateHeader("Time:",date.getTime());
}

response向客户端写入数据-LMLPHP

3、response对象设置响应头:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Date date=new Date(121344444);
response.addHeader("zzz","I love JAVA.");
response.addIntHeader("myself",22);
response.addDateHeader("Time:",date.getTime());
response.setIntHeader("myself",23);
}

response向客户端写入数据-LMLPHP

05-11 22:18