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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM