Servlet输出流getOutputStream()

实例代码:

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

  
    $Title$
  
  
  

inputStreamServlet.java

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;



@WebServlet(name = "Servlet",urlPatterns = "/download")
public class inputStreamServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = request.getParameter("name");

        if(name.equals("name")){
            response.setContentType("application/pdf");//设置显示内容类型
            InputStream in = getServletContext().getResourceAsStream("/WEB-INF/a.pdf");//获得输入流

            OutputStream out = response.getOutputStream();//取得输出流
            writeBytes(in,out);//读取文件并显示在浏览器
        }
    }
    //writeBytes()构造方法
    private void writeBytes(InputStream in, OutputStream out) throws IOException {
        byte[] buffer= new byte[1024];
        int length = -1;
        while ((length = in.read(buffer))!=-1){
            out.write(buffer,0,length);

        }
        in.close();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

你可能感兴趣的:(Servlet输出流getOutputStream())