JavaWeb 入门篇(4)HttpResponse 详解 HttpRequest 详解
HttpResponse 講解
HttpServletResponse概述:
? 在創建Servlet時會覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個參數,一個為代表請求的request和代表響應response。service方法中的response的類型是ServletResponse,而doGet/doPost方法的response的類型是HttpServletResponse,HttpServletResponse是ServletResponse的子接口,功能和方法更加強大。
Response運行流程
響應頭有很多這里只介紹常用的。
在瀏覽器可以按F12 抓包看響應頭、請求頭、具體的可以再查。
設置響應行
設置響應的狀態碼
/*** @Author: crush* @Date: 2021-05-09 19:35* version 1.0*/ @WebServlet("/test3") public class HttpResponseTest3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("設置狀態碼,前臺通過判斷狀態碼,來判斷請求是否成功");resp.setStatus(404);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }測試
設置響應頭
刷新 跳轉頁面
/*** @Author: crush* @Date: 2021-05-09 19:35* version 1.0*/ @WebServlet("/test4") public class HttpResponseTest4 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 設置響應頭 每1秒自動刷新System.out.println("設置響應頭 每1秒自動刷新");resp.setHeader("Refresh", "1");//定時跳轉 3秒后將自動跳轉 // resp.setHeader("Refresh","3;URL=hello.jsp");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }測試
一個小demo 實現刷新 頁面累加
/*** response* @author Adimi*/ @WebServlet("/test4") public class ResponseTest4 extends HttpServlet {private static Integer id=1;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setHeader("Refresh","1");PrintWriter writer = response.getWriter();id++;writer.print("id==>"+id);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }設置字符編碼 解決中文亂碼問題
/*** @Author: crush* @Date: 2021-05-09 19:35* version 1.0*/ @WebServlet("/test1") public class HttpResponseTest1 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 解決中文亂碼問題// 設置響應頭// 設置字符編碼 resp.setCharacterEncoding("UTF-8");// 設置響應內容以什么格式展示到頁面 什么編碼格式 包含了設置字符編碼resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();writer.print("中國,你好!!!");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }測試
重定向 redirect
/*** 重定向* @Author: crush* @Date: 2021-05-09 19:35* version 1.0*/ @WebServlet("/test5") public class HttpResponseTest5 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.sendRedirect("hello.jsp"); // resp.setHeader("location","www.baidu.com"); 通過設置響應頭轉發}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }request轉發
/*** 重定向* @Author: crush* @Date: 2021-05-09 19:35* version 1.0*/ @WebServlet("/test5") public class HttpResponseTest5 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.sendRedirect("hello.jsp");req.getRequestDispatcher("hello.jsp").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }重定向和轉發的區別
文件下載
獲取路徑資源
String path=this.getServletContext().getRealPath("WEB-INF\\classes\\8.jpg");讀取資源
FileInputStream fileInputStream=new FileInputStream(path);獲取到文件名,路徑在電腦上保存的形式是 \ \
String fileName=path.substring(path.lastIndexOf("\\")+1);設置消息頭告訴瀏覽器,我要下載1.png這個圖片 設置編碼
resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));把讀取到的內容回送給瀏覽器
int len=0; byte[] bytes=new byte[1024]; // ServletOutputStream 提供用于將二進制數據發送到客戶端的輸出流 ServletOutputStream servletOutputStream=resp.getOutputStream(); while((len=fileInputStream.read(bytes))>0) {servletOutputStream.write(bytes,0,len); }關閉資源
注:8.jpg 放在我的resources 文件夾下 但是這里需要寫的是編譯完8.jpg存放的位置
具體代碼
/*** @Author: crush* @Date: 2021-05-09 19:40* version 1.0*/ @WebServlet("/down") public class ResponseDownFile extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//獲取路徑資源String path=this.getServletContext().getRealPath("WEB-INF\\classes\\8.jpg");//讀取資源FileInputStream fileInputStream=new FileInputStream(path);//獲取到文件名,路徑在電腦上保存的形式是\\String fileName=path.substring(path.lastIndexOf("\\")+1);//設置消息頭告訴瀏覽器,我要下載1.png這個圖片// 該方式文件名為中文時會亂碼//防止中文亂碼resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));//把讀取到的內容回送給瀏覽器int len=0;byte[] bytes=new byte[1024];ServletOutputStream servletOutputStream=resp.getOutputStream();while((len=fileInputStream.read(bytes))>0) {servletOutputStream.write(bytes,0,len);}// 關閉資源servletOutputStream.close();fileInputStream.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }HttpRequest 講解
HttpServletRequest概述
? 我們在創建Servlet時會覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個參數,一個為代表請求的request和代表響應response。service()方法中寫了根據請求方式的不同調用doget()和dopost().
service方法中的request的類型是ServletRequest,而doGet/doPost方法的request類型HttpServletRequest,HttpServletRequest是ServletRequest的子接口,功能和方法更加強大.
Request 運行流程
獲取請求攜帶的參數
/*** @Author: crush* @Date: 2021-05-11 16:52* version 1.0*/ @WebServlet("/request1") public class RequestTest1 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 這里是請求的參數名 必須是同名的 String username = req.getParameter("username"); String password = req.getParameter("password");PrintWriter writer = resp.getWriter();writer.print("<h1>"+username+":"+password+"</h1>");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }獲取多個參數的值
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 設置請求的編碼 不然會亂碼req.setCharacterEncoding("utf-8");Enumeration<String> names = req.getParameterNames();while (names.hasMoreElements()) {String name = (String) names.nextElement();String[] values = req.getParameterValues(name);System.out.println(name+":"+ Arrays.toString(values));}}獲得請求行的信息
/*** @Author: crush* @Date: 2021-05-11 16:52* version 1.0*/ @WebServlet("/request3") public class RequestTest3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 獲得請求的urlStringBuffer requestURL = req.getRequestURL();System.out.println("請求的URL===>"+requestURL);// 獲得請求的Servlet的路徑String path = req.getServletPath();System.out.println("請求的Servlet的路徑===>"+path);//返回發出此請求的HTTP方法的名稱,例如GET,POST或PUTString method = req.getMethod();System.out.println("返回發出此請求的HTTP方法的名稱==>"+method);//返回發送請求的客戶端或最后一個代理的Internet協議(IP)地址String remoteAddr = req.getRemoteAddr();System.out.println("remoteAddr==>"+remoteAddr);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }request實現轉發
/*** @Author: crush* @Date: 2021-05-11 16:52* version 1.0*/ @WebServlet("/request2") public class RequestTest2 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 訪問request2 轉發到 request4去req.getRequestDispatcher("/request4").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }request是一個域對象
request對象也是一個存儲數據的區域對象,所以也具有如下方法:
setAttribute(String name, Object o)
getAttribute(String name)
removeAttribute(String name)
ServletContext 作用域:
創建:啟動web應用程序的時候創建
銷毀:關閉web應用程序的時候銷毀
域的作用范圍:整個web應用的啟動周期
request作用域:
創建:訪問時創建request
銷毀:響應結束request銷毀
域的作用范圍:一次請求中
自言自語
努力生活、加油學習。
總結
以上是生活随笔為你收集整理的JavaWeb 入门篇(4)HttpResponse 详解 HttpRequest 详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新闻系统粗略说明文档
- 下一篇: Java 多线程模拟卖票