HttpServletRequest、HttpServletResponse、Cookie、Session

获取客户端请求过来的参数: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

1、获取前段传递的参数

主要使用getParameter和getParameterValues,后者接收数组

.getAttributes setAttributes 只能用于当前Request,在list.jsp中使用

ServletActionContext.getRequest().setAttribute("list", list);
return "list";

 

2、转发请求

req.getRequestDispatcher("xxx.jsp").forward(req,resp);

 

保存会话的两种技术

Cookie

客户端技术,通过客户端请求,服务器响应实现,保存在客户端

Session

服务器技术,可以保存数据信息

手动注销:session.invalidate();

web.xml设置会话超时:session-config session-timeout

 

posted @ 2020-02-09 00:24  Alan*Chen  阅读(1728)  评论(0编辑  收藏  举报