/** * Servlet implementation class HelloServlet */ @WebServlet("/HelloServlet") public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HelloServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //this.execute(request, response); //this.test1(response); //this.test2(response); //this.test3(response); test5(response); } private void test5(HttpServletResponse response) throws IOException { response.setHeader("content-disposition", "attachment;filename=apple.png"); InputStream in = this.getServletContext().getResourceAsStream("/apple.png"); int len = 0; byte[] buffer = new byte[1024]; OutputStream out = response.getOutputStream(); while( (len=in.read(buffer)) >0 ) { out.write(buffer, 0, len); } } public void test4( HttpServletResponse response) throws IOException { response.setHeader("refresh", "3;url='http://www.baidu.com'"); // will goto baidu after 3s String data = "refresh"; response.getOutputStream().write(data.getBytes()); } public void test3( HttpServletResponse response) throws IOException { response.setHeader("content-type", "image/png"); InputStream in = this.getServletContext().getResourceAsStream("/apple.png"); int len = 0; byte[] buffer = new byte[1024]; OutputStream out = response.getOutputStream(); while( (len=in.read(buffer)) >0 ) { out.write(buffer, 0, len); } } public void test2( HttpServletResponse response) throws IOException { String data = "jskdljasldjasldjsdlkasjdlkasjdlskdjd"; System.out.println("before size is: " + data.getBytes().length); ByteArrayOutputStream bout = new ByteArrayOutputStream(); GZIPOutputStream gout = new GZIPOutputStream(bout); gout.write(data.getBytes()); gout.close(); byte[] gzip = bout.toByteArray(); System.out.println("after size is: " + gzip.length); response.setHeader("Content-Encoding", "gzip"); response.setHeader("Content-Length", gzip.length+""); response.getOutputStream().write(gzip); } public void test1( HttpServletResponse response) { response.setStatus(302); response.setHeader("location", "/WebTest/1.html"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //this.execute(request, response); } }