HttpServletRequest和HttpServletResponse

获取客户端请求过来的参数:HttpServletRequest

获取给客户端响应的信息:HttpServletResponse

HttpServletResponse

常见应用:

1、向浏览器输出信息

PrintWriter writer = resp.getWriter();
writer.print("Hello,Servlet");

 

2、下载文件

//实现Servlet接口
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取下载文件路径,绝对路径
            String filepath= "";
        //定义文件名对象
            String filename = filepath.substring(filepath.lastIndexOf("\\")+1);
        //设置浏览器下载支持Content-Disposition,中文文件名URLEncoder.encode编码
            resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
        //获取下载文件的输入流
            FileInputStream fis = new FileInputStream(filepath);
        //创建缓冲区
            int length = 0;
            byte[] buffer = new byte[1024];
        //获取outputstream对象
            ServletOutputStream out = resp.getOutputStream();
        //将FileOutputStream流写入buffer缓冲区,使用outputstream将缓冲区中的数据输出到客户端
            while((length=fis.read(buffer))>0){
                out.write(buffer,0,length);
            }
        //关闭流
        fis.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

3、验证码功能(略)

重定向:

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/项目路径/xxx");
    }

 

你可能感兴趣的:(HttpServletRequest和HttpServletResponse)