JavaWeb(六)——HttpServletResponse、HttpServletRequest
文章目錄
- 1. HttpServletResponse
- 1.1 簡單分類
- 1.2 下載文件
- 1.3 驗證碼功能
- 1.4 實現重定向
- 1.5 簡單實現登錄重定向
- 2. HttpServletRequest
1. HttpServletResponse
web服務器接收到客戶端的http請求,針對這個請求,分別創建一個代表請求的HttpServletRequest對象,代表響應的一個HttpServletResponse;
- 如果要獲取客戶端請求過來的參數:找HttpServletRequest
- 如果要給客戶端響應一些信息:找HttpServletResponse
1.1 簡單分類
負責向瀏覽器發送數據的方法
ServletOutputStream getOutputStream() throws IOException; 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);void addDateHeader(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 下載文件
(1)向瀏覽器輸出消息:具體可查看之前筆記
ServletOutputStream getOutputStream() throws IOException; PrintWriter getWriter() throws IOException;(2)下載文件
①要獲取下載文件的路徑
②下載的文件名是啥?
③設置想辦法讓瀏覽器能夠支持下載我們需要的東西
④獲取下載文件的輸入流
⑤創建緩沖區
⑥獲取OutputStream對象
⑦將FileOutputStream流寫入到buffer緩沖區
⑧使用OutputStream將緩沖區中的數據輸出到客戶端
- 創建的文件目錄如下
- FileServlet 文件里的代碼如下:
web.xml 文件的里的代碼如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"metadata-complete="true"><servlet><servlet-name>filedown</servlet-name><servlet-class>com.zz.servlet.FileServlet</servlet-class></servlet><servlet-mapping><servlet-name>filedown</servlet-name><url-pattern>/down</url-pattern></servlet-mapping>- 測試訪問結果:
1.3 驗證碼功能
驗證怎么來的?
- 前端實現
- 后端實現,需要用到 Java 的圖片類,生產一個圖片
ImageServlet 文件里的代碼如下:
package com.zz.servlet;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 ImageServlet extends HttpServlet {@Overrideprotected 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 g = (Graphics2D) image.getGraphics(); //筆//設置圖片的背景顏色g.setColor(Color.white);g.fillRect(0,0,80,20);//給圖片寫數據g.setColor(Color.BLUE);g.setFont(new Font(null,Font.BOLD,20));g.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());}//生成隨機數private String makeNum(){Random random = new Random();String num = random.nextInt(9999999) + "";StringBuffer sb = new StringBuffer();for (int i = 0; i < 7-num.length() ; i++) {sb.append("0");}num = sb.toString() + num;return num;}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }web.xml 文件的里添加代碼如下:
<servlet><servlet-name>ImageServlet</servlet-name><servlet-class>com.zz.servlet.ImageServlet</servlet-class></servlet><servlet-mapping><servlet-name>ImageServlet</servlet-name><url-pattern>/img</url-pattern></servlet-mapping>- 測試訪問結果:
1.4 實現重定向
B一個web資源收到客戶端A請求后,B會通知A客戶端去訪問另外一個web資源C,這個過程叫重定向
常見場景:用戶登錄
//使用的方法 void sendRedirect(String var1) throws IOException;RedirectServlet 文件里的代碼如下:
package com.zz.servlet;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 RedirectServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/*resp.setHeader("Location","/r/img");resp.setStatus(302);*/resp.sendRedirect("/r/img");//重定向}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }web.xml 文件的里添加代碼如下:
<servlet><servlet-name>RedirectServlet</servlet-name><servlet-class>com.zz.servlet.RedirectServlet</servlet-class></servlet><servlet-mapping><servlet-name>RedirectServlet</servlet-name><url-pattern>/red</url-pattern></servlet-mapping>測試訪問結果:
輸入red ,結果跳轉到img 界面
面試題:請你聊聊重定向和轉發的區別?
相同點
- 頁面都會實現跳轉
不同點
- 請求轉發的時候,url不會產生變化 307
- 重定向時候,url地址欄會發生變化 302
1.5 簡單實現登錄重定向
index.jsp文件中代碼為:
<html> <body> <h2>Hello World!</h2><%--這里提交的路徑,需要尋找到項目的路徑--%> <%--${pageContext.request.contextPath}代表當前的項目--%><form action="${pageContext.request.contextPath}/login" method="get">用戶名:<input type="text" name="username"> <br>密碼:<input type="password" name="password"> <br><input type="submit"> </form></body> </html>RequestTest文件中的代碼為:
package com.zz.servlet;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 RequestTest extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//處理請求String username = req.getParameter("username");String password = req.getParameter("password");System.out.println(username+":"+password);//重定向時候一定要注意,路徑問題,否則404;resp.sendRedirect("/r/success.jsp");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }web.xml 文件的里添加代碼如下:
<servlet><servlet-name>requset</servlet-name><servlet-class>com.zz.servlet.RequestTest</servlet-class></servlet><servlet-mapping><servlet-name>requset</servlet-name><url-pattern>/login</url-pattern></servlet-mapping>創建一個success.jsp 文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body><h1>Success</h1></body> </html>測試訪問結果:
2. HttpServletRequest
HttpServletRequest代表客戶端的請求,用戶通過Http協議訪問服務器,HTTP請求中的所有信息會被封裝到HttpServletRequest,通過這個HttpServletRequest的方法,獲得客戶端的所有信息,主要有如下應用。
獲取參數,請求轉發
只學上面的第一個和第四個方法
LoginServlet 文件中的代碼為:
package com.zz.servlet;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays;public class LoginServlet extends HttpServlet {@Overrideprotected 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應用,因此地址欄不用加/rreq.getRequestDispatcher("/success.jsp").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }index.jsp文件中代碼為:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body> <h1>登錄</h1><div><%--這里表單作用為:以post方式提交表單,提交至login請求--%><form action="${pageContext.request.contextPath}/login" method="post">用戶名:<input type="text" name="username" required><br> <%--required作為非空判斷--%>密碼:<input type="password" name="password"><br>愛好:<input type="checkbox" name="hobbys" value="美女">美女<input type="checkbox" name="hobbys" value="音樂">音樂<input type="checkbox" name="hobbys" value="代碼">代碼<input type="checkbox" name="hobbys" value="學術">學術<br><input type="submit"></form> </div> </body> </html>web.xml 文件的里添加代碼如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"metadata-complete="true"><servlet><servlet-name>LoginServlet</servlet-name><servlet-class>com.zz.servlet.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/login</url-pattern></servlet-mapping></web-app>創建一個success.jsp 文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body> <h1>登陸成功!</h1> </body> </html>測試訪問結果:
總結
以上是生活随笔為你收集整理的JavaWeb(六)——HttpServletResponse、HttpServletRequest的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaWeb(五)——Servlet、
- 下一篇: JavaWeb(七)——Cookie、S