Servlet 04 ----【javaweb-07】
SERVLET
HttpServletResponse && HttpServletRequest
在web伺服器接收到客戶端的請求時,會分別建立兩個物件:HttpServletResponse && HttpServletRequest
如果要獲取客戶端請求過來的資料,則須使用HttpServletRequest
如果要給客戶端響應一些資訊,則須使用HttpServletResonse
1、 HttpServletResponse
1.1、分類
一些負責向瀏覽器傳送資料的常用方法:
ServletOutputStream getOutputStream() throwsIOException; PrintWriter getWriter() throws IOException;
一些負責向瀏覽器傳送響應頭的方法:
void setCharacterEncoding(String var1); void setContentLength(int var1); void setContentLengthLong(long var1); void setContentType(String var1); void setDateHeader(String var1, long var2); voidaddDateHeader(String var1, long var2); void setHeader(String var1, String var2); void addHeader(String var1, String var2); void setIntHeader(String var1, int var2); void addIntHeader(String var1, int var2);
一些響應的狀態碼
int SC_CONTINUE = 100; int SC_SWITCHING_PROTOCOLS = 101;int SC_OK = 200; int SC_CREATED = 201; int SC_ACCEPTED = 202; int SC_NON_AUTHORITATIVE_INFORMATION = 203; int SC_NO_CONTENT = 204; int SC_RESET_CONTENT = 205; int SC_PARTIAL_CONTENT = 206; int SC_MULTIPLE_CHOICES = 300; int SC_MOVED_PERMANENTLY = 301; int SC_MOVED_TEMPORARILY = 302; int SC_FOUND = 302; int SC_SEE_OTHER = 303; int SC_NOT_MODIFIED = 304; int SC_USE_PROXY = 305; int SC_TEMPORARY_REDIRECT = 307; int SC_BAD_REQUEST = 400; int SC_UNAUTHORIZED = 401; int SC_PAYMENT_REQUIRED = 402; int SC_FORBIDDEN = 403; int SC_NOT_FOUND = 404; int SC_METHOD_NOT_ALLOWED = 405; int SC_NOT_ACCEPTABLE = 406; int SC_PROXY_AUTHENTICATION_REQUIRED = 407; int SC_REQUEST_TIMEOUT = 408; int SC_CONFLICT = 409; int SC_GONE = 410; int SC_LENGTH_REQUIRED = 411; int SC_PRECONDITION_FAILED = 412; int SC_REQUEST_ENTITY_TOO_LARGE = 413; int SC_REQUEST_URI_TOO_LONG = 414; int SC_UNSUPPORTED_MEDIA_TYPE = 415; int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; int SC_EXPECTATION_FAILED = 417; int SC_INTERNAL_SERVER_ERROR = 500; int SC_NOT_IMPLEMENTED = 501; int SC_BAD_GATEWAY = 502; int SC_SERVICE_UNAVAILABLE = 503; int SC_GATEWAY_TIMEOUT = 504; int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
1.2、下載檔案
首先,瞭解一些下載檔案的過程。
- 獲取下載檔案的路徑
- 下載的檔名
- 設定讓瀏覽器支援下載我們需要的東西
- 獲取下載檔案的輸入流
- 建立緩衝區
- 獲取OutputStream物件
- 將FileOutputStream流寫入buffer緩衝區
- 使用OutputStream將緩衝區中的資料輸出到客戶端
程式碼實現:
package com.charles.responce; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; public class Down extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1. 要獲取下載檔案的路徑 String realPath = "D:\\JavaProject\\Demo05\\Java_Web_Response\\src\\main\\resources\\123.jpg"; System.out.println("檔案路路徑:"+ realPath); // 2. 下載的檔名是啥? String fileName = realPath.substring(realPath.indexOf("\\") + 1); // 3. 設定想辦法讓瀏覽器能夠支援下載我們需要的東西 resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")); // 4. 獲取下載檔案的輸入流 FileInputStream in = new FileInputStream(realPath); // 5. 建立緩衝區 int len = 0; byte[] buffer = new byte[1024]; // 6. 獲取OutputStream物件 ServletOutputStream out = resp.getOutputStream(); // 7. 將FileOutputStream流寫入到buffer緩衝區,使用OutputStream將緩衝區中的資料輸出到客戶端! if ((len = in.read(buffer)) != 1){ out.write(buffer,0,len); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
註冊servlet後,結果展示:可以看到,頁面跳轉後,瀏覽器自動下載該圖片。
1.3、驗證碼功能
案例:建立一個圖片數字驗證碼
程式碼實現:
package com.charles.responce; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; public class ImgServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 設定瀏覽器每3秒重新整理一次 resp.setHeader("refresh", "3"); // 在記憶體中建立一個圖片 BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); // 得到圖片 Graphics2D graphics2D = (Graphics2D) image.getGraphics(); // 筆 // 設定圖片的背景顏色 graphics2D.setColor(Color.white); graphics2D.fillRect(0,0,80,20); // 給圖片寫資料 graphics2D.setColor(Color.blue); graphics2D.setFont(new Font(null,Font.ITALIC,20)); graphics2D.drawString(makeNum(),0,20); // 告訴瀏覽器,請求用圖片方式開啟 resp.setContentType("image/jpeg"); // 網站存在快取,不讓瀏覽器快取 resp.setDateHeader("expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); // 把圖片寫給瀏覽器 ImageIO.write(image,"jpg",resp.getOutputStream()); } // 生成隨機數 public String makeNum(){ Random rd = new Random(); String num = rd.nextInt(9999) + " "; StringBuffer sb = new StringBuffer(); for (int i = 0; i < 7-num.length(); i++) { sb.append("0"); } num = sb.toString() + num; return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
註冊servlet後,結果展示:
1.4、重定向
重定向(Redirect)就是通過各種方法將各種網路請求重新定個方向轉到其它位置
登入案例:
程式碼展示:
1. 首頁的jsp頁面:
<html> <body> <form action="${pageContext.request.contextPath}/login" method="get"> username <input type="text" name="username"> <br> password <input type="password" name="password"> <br> <input type="submit"> </form> </body> </html>
2. 重定向的jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>Success!!!!!</h1> </body> </html>
3. servlet類
package com.charles.responce; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class login extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("GBK"); // 處理請求 String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username + ": " + password); // 重定向 resp.sendRedirect("/r/success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
註冊servlet後,執行結果展示:
1. 隨便輸入一個賬號密碼
2. 提交資料後,頁面重定向至成功頁面
3. 控制檯展示
2. HttpServletRequest
HttpServletRequest代表客戶端的請求,使用者通過Http協議訪問伺服器,HTTP請求中的所有資訊會被封裝到HttpServletRequest,通過這個HttpServletRequest的方法,獲得客戶端的所有資訊;
在這裡提供一個小案例,來展示Request的使用方法:
程式碼展示:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println("============================="); //後臺接收中文亂碼問題 System.out.println(username); System.out.println(password); System.out.println(Arrays.toString(hobbys)); System.out.println("============================="); System.out.println(req.getContextPath()); //通過請求轉發 //這裡的 / 代表當前的web應用 req.getRequestDispatcher("/success.jsp").forward(req,resp); }
展示的jsp頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <div style="align-content: center"> <form action="${pageContext.request.contextPath}/login" method="post"> 使用者名稱:<input type="text" name="username"> 密碼:<input type="password" name="password"> 愛好: <input type="checkbox" name="hobbies" value="code">code <input type="checkbox" name="hobbies" value="dance">dance <input type="checkbox" name="hobbies" value="sing">sing <input type="checkbox" name="hobbies" value="swim">swim <input type="submit"> </form> </div> </body> </html>
跳轉的jsp頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <hi>Success!!!!</hi> </body> </html>
註冊servlet後,執行展示:
以上程式碼學自狂神說Java:https://space.bilibili.com/95256449?from=search&seid=14414140126489464870