public class ResponseServlet extends HttpServlet { /** * 1、tomcat服务器把请求信息封装到HttpServletRequest对象,且把响应信息封装到HttpServletResponse * 2、tomcat服务器调用doGet方法,传入request,和response对象 * 3、通过response对象改变响应信息 * 4、tomcat服务器把response对象的内容转换成响应格式内容,再发送给浏览器解析 * @param request * @param response * @throws ServletException * @throws IOException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 设置响应实体内容编码 */ //response.setCharacterEncoding("utf-8"); /** * 3.1 响应行 */ //修改状态码 //response.setStatus(404); // 发送404的状态码+404的错误页面 //response.sendError(404); /** * 3.2 响应头 */ //response.setHeader("server", "JBoss"); /** * 3.3 实体内容(浏览器直接能够看到的内容就是实体内容) */ //字符内容。 //response.getWriter().write("hello world"); //字节内容 //response.getOutputStream().write("hello world".getBytes()); /** * 请求重定向: 发送一个302状态码 + location的响应头 */ //发送一个302状态码 //response.setStatus(302); //location的响应头 //response.setHeader("location", "/myweb/adv.html"); //请求重定向简化写法 //response.sendRedirect("/myweb/adv.html"); /** * 定时刷新 * 原理:浏览器认识refresh头,得到refresh头之后重新请求当前资源 */ //每隔1秒刷新次页面 //response.setHeader("refresh", "1"); /** * 隔n秒之后跳转另外的资源 */ //隔3秒之后跳转到adv.html //response.setHeader("refresh", "3;url=/myweb/adv.html"); // 打开图片 /*response.setContentType("image/jpg"); File file = new File("e://test.jpg"); FileInputStream inputStream = new FileInputStream(file); int len = 0; byte[] byt = new byte[1024]; while ((len = inputStream.read(byt)) != -1){ response.getOutputStream().write(byt,0,len); }*/ // 以下载的方式打开图片 File file = new File("e://image.jpg"); FileInputStream inputStream = new FileInputStream(file); response.setHeader("Content-Disposition","attachment; filename="+file.getName()); int len = 0; byte[] byt = new byte[1024]; while ((len = inputStream.read(byt)) != -1){ response.getOutputStream().write(byt,0,len); } } /** * * @param request * @param response * @throws ServletException * @throws IOException */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }