HttpServletResponse response realizes file upload and download

I. Overview

The service() method, or doGet()/doPost(), is overridden when creating a servlet. These methods have two parameters, one is the request representing the request and the response representing the response. The response type in the service method is ServletResponse, and the response type of the doGet/doPost method is HttpServletResponse. HttpServletResponse is a sub-interface of ServletResponse with more powerful functions and methods.

Second, the operation process of response

Three, grab the http response through the packet capture tool

 

Four, detailed explanation of http response header information

1、server

The response header is the server tells the browser, the current response service type and version.

2. Content-Type response header

The server tells the browser what type of response content and what character encoding is used. The value of the response header is now text/html;charset=utf-8. Explain that the type of response information is html in the text type, and the character encoding used is utf-8.

3. Content-Length response header

The server tells the browser that the Content-Length response header indicates the size of the response entity, and the length of the response content is now 312 bytes.

4. Data response header

Indicates when the server responded to the browser. Note that the time here is calculated based on US time.

5、 Accept-Ranges: bytes

The response header indicates that the server supports Range requests, and the unit supported by the server is byte (this is also the only available unit). We can also know: the server supports resumable uploads and supports downloading multiple parts of files at the same time. That is to say, the download tool can use the range request to speed up the download of the file. The Accept-Ranges:  none  response header indicates that the server does not support the range request.

6、Last-Modified

Last modification time of the file on the server

Five, set the response content

 response represents the response, and the Http response can be set separately through this object: response line response header response body

1. Set the status code of the response line

setStatus(int value)

response.setStatus(302);

2. Set the response header

addHeader(String name,String value)
addIntHeader(String name,int value)
addDateHeader(String name,long value)

public class HeaderServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 Date date = new Date();
		 response.addHeader("name", "xiaodingdang");
		 response.addHeader("name", "daxiong");
		 response.addIntHeader("age", 15);
		 response.addDateHeader("birthday", date.getTime());
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Note that the difference between setHeader and addHeader is that setting one is adding the setting can only be the last one, but adding can add many.

3. The response implements redirection

method one:

response.setStatus(302); //设置响应行的状态码为302 重定向
response.setHeader("Location", "/Servlet/servlet2"); //设置响应头的属性 跳转到Servlet2

Method Two:

response.sendRedirect("/Servlet/servlet2"); //利用response中的sendRedirect属性完成重定向

4. Response realizes automatic refresh jump

public class RefreshServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("refresh", "5;url=http://www.baidu.com"); //设置头 参数 数值5为
		//秒 中间用分号间隔 url为要跳转的网址
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Use JS to complete automatic jump

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	window.onload= function(){
		var time = 3;
		var second = document.getElementById("second");
		timer = setInterval(function(){
			second.innerHTML = time;
			time--;
			if(time==0){
				location.href = "http://www.baidu.com";
				clearInterval(timer);
			}
		},1000);
	}
</script>
</head>
<body>
	恭喜你,登录成功,<span id="second" style="color: red">3</span>秒后将跳转,若不跳转 请点击<a href="http://www.baidu.com">这里</a>
</body>
</html>

5. Solve the Chinese garbled response problem

//方法一:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-Type", "text/html;charset=utf-8");
		response.getWriter().write("小叮当");
		
	}
//方法二:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.setCharacterEncoding("UTF-8");
//		response.setHeader("content-Type", "text/html;charset=utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("中国");
		
	}
//通常使用第二种方法解决乱码问题

6. Upload image resources

public class TestServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream outputStream = response.getOutputStream(); //获得字节输出流
		String realPath = this.getServletContext().getRealPath("1.jpg"); //获得图片的真实路径
		InputStream in = new FileInputStream(realPath); //获得服务器上的图片
		
		//使用高效的方法写入客户端图片
		int len = 0;
		byte[] buffer = new byte[1024];
		while((len=in.read(buffer))>0) {
			outputStream.write(buffer, 0, len);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

7. Realize file download

public class ResponseFileServlet extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
      downfile(response);
   }
 
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
      downfile(response);
   }
 
   private void downfile(HttpServletResponse response) throws IOException {
   //获取下载的文件路径(注意获取这里获取的是绝对路径,先获取ServletContext再使用ServletContext的getRealPath方法获取绝对路径)
   String path = this.getServletContext().getRealPath("/Resourse/Student.xml");
   //设置响应头控制浏览器以下载的形式打开文件
   response.setHeader("content-disposition","attachment;fileName="+"Student.xml");
   InputStream in = new FileInputStream(path); //获取下载文件的输入流
   int count =0;
   byte[] by = new byte[1024];
   //通过response对象获取OutputStream流
   OutputStream out=  response.getOutputStream();
   while((count=in.read(by))!=-1){
      out.write(by, 0, count);//将缓冲区的数据输出到浏览器
   }
   in.close();
   out.flush();
   out.close();
}}

As can be seen from the above code, the idea of ​​using Response to download files is mainly divided into:

First get the absolute path of the downloaded file, and then set the response header (content-disposition) to tell the browser to open the file as a download, then use InputStream to get the input stream of the downloaded file, create a data buffer, and get the OutputStream through the response object Stream, write the FileInputStream stream into the byte array, and use OutpuStream to output the byte array data to the browser.

note:

(1) The output stream obtained by the response does not need to be closed manually, the Tomcat container will help us to close
it, but the InputStream needs to be closed manually
(2) getWriter and getOutputStream cannot be called at the same time

 

Previous: [Summary of the most complete Java framework in the full stack] SSH, SSM, Springboot

Next: Hibernate basic knowledge summary (absolutely classic)

 

Reference: https://blog.csdn.net/fanbaodan/article/details/84846872

Guess you like

Origin blog.csdn.net/guorui_java/article/details/111145510