請求和轉發:
- response說明
- 一、response文件下載
- 二、response驗證碼實現
- 1.前置知識:
- 2.具體實現:
- 3.知識總結
- 三、response重定向
- 四、request轉發
- 五、重定向和轉發的區別
response說明
response是指HttpServletResponse,該響應有很多的應用,比如像瀏覽器輸出消息,下載文件,實現驗證碼等。
一、response文件下載
1.創建一個javaweb的項目。
2.實例類FileServlet的具體實現。
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.獲取要下載文件的路徑 realPath:絕對路徑String realPath = "E:\\Software\\IDEA\\javaweb-02-servlet\\response\\src\\main\\resources\\aa.webp";System.out.println("文件下載的路徑:" + realPath);
// 2.下載的文件名String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3.設置瀏覽器能夠支持下載我們需要的東西
// 如果想讓網站能下載東西,需要搜一個下載文件的一個頭。
// resp.setHeader("Content-disposition", "attachment;filename" + fileName);resp.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
// 4.獲取下載文件的輸入流。FileInputStream fis = new FileInputStream(realPath);
// 5.創建緩沖區
// 6.獲取OutputStream對象
// 7.將FileOutputStream流寫入到緩沖區,使用OutputStream將緩沖區中的數據輸出到客戶端。ServletOutputStream oos = resp.getOutputStream();byte[] buf = new byte[1024];int len = 0;while ((len = fis.read(buf)) > 0) {oos.write(buf, 0, len);}oos.close();fis.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
3.配置web.xml文件及tomcat服務器。
4.啟動服務。
5.回顧總結
- (5.1)思路分析:
- 1.獲取文件輸入流
- 2.獲取web的響應的輸出流
- 3.將輸入流寫入到輸出流,進而發給客戶端。
- (5.2)注意實項:
- 1.下載文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
- 2.下載文件的頭
resp.setHeader("Content-disposition", "attachment;filename" + fileName);
- 3.相關搜索
二、response驗證碼實現
1.前置知識:
下載文件需要一個響應頭,響應瀏覽器的類型是:
resp.setHeader("Content-disposition", "attachment;filename" + fileName);
而圖片驗證碼需要設置 發送到客戶端的響應的內容類型
resp.setContentType("image/jpg");
以jsp的形式發送的圖片類型。
此外,也可以是png,jepg等形式。
還需要設置每60s刷新一次:
resp.setHeader("refresh","60");
常見的內容類型:
resp.setContentType("text/html");
以html的格式響應的文本類型,即代表響應的是html頁面。
2.具體實現:
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 {
//如何讓瀏覽器每60s自動刷新一次resp.setHeader("refresh","60");// 在內存中創建一個圖片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.CYAN);g.setFont(new Font(null,Font.BOLD,20));g.drawString(makeNum(),0,20);// 告訴瀏覽器,這個請求用圖片的方式打開
// setContentType 設置發送到客戶端的響應的內容類型resp.setContentType("image/jpg");
//網站存在緩存,不讓瀏覽器去緩存
// setHeader設置響應頭
// setDateHeader 是設置頁面緩存的,防止 JSP或者Servlet中的輸出 被瀏覽器保存在緩沖區中。resp.setDateHeader("Expires",-1);//在代理服務器端防止緩沖resp.setHeader("Cache-Control","no-cache");resp.setHeader("Pragma","no-cache");// 把圖片寫給瀏覽器ImageIO.write(image,"jpg",resp.getOutputStream());}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}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;}
}
3.知識總結
(1)設置瀏覽器自動刷新。
(2)清除瀏覽器緩存。
(3)將圖片寫給瀏覽器。(可以試試其他的內容,比如音樂電影什么行不行?)
(4)設置客戶端的響應內容形式為圖片。
(5)內存中創建圖片,并通過畫筆類進行操作。
(ImageIO是一個圖片類,專門寫圖片的。)
(6)生成隨機數。
畫筆是如果要寫文字,要先選定顏色,然后選定字體,文本框,在哪個位置開始寫。
三、response重定向
如:
resp.sendRedirect("/re/img1");
即 resp.sendRedirect("/項目映射名/跳轉的頁面的映射");
也可以跳轉到jsp頁面。
實例代碼:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<%--這里提交的路徑 需要尋找到項目的路徑--%>
<form action="${pageContext.request.contextPath}/login" method="get">用戶名:<input type="text" name="username">密碼:<input type="password" name="password"><input type="submit">
</form>
</body>
</html>
public class RedirectServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// redirect 重定向resp.sendRedirect("/re/img1");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
四、request轉發
request處理請求:
HTTP請求中的所有信息被封裝到HttpServletRequest對象,通過該對象的方法,可以獲取客戶端的所有信息。
主要的獲取參數的兩種方法:
實例代碼:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>登錄</title>
</head>
<body>
<h1>登錄</h1>
<div style="text-align: center">
<%--以post方式提交表單,提交到我們的login請求--%><form action="${pageContext.request.contextPath}/login" method="post">用戶名:<input type="text" name="username"><br>密碼:<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>
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+":"+password);System.out.println(Arrays.toString(hobbys));System.out.println("================");
//請求轉發 req
// /被解析成當前項目路徑req.getRequestDispatcher("/success.jsp").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
五、重定向和轉發的區別
相同點:
- 頁面都會實現跳轉。
不同點:
- 請求轉發的時候,url不會發生改變。
轉發時:
req.getRequestDispatcher("/success.jsp").forward(req,resp);
- 重定向的時候,url地址欄會發送改變。
重定向:
resp.sendRedirect("/re/img1");