JavaWeb入門(mén):HttpResponse和HttpRequest詳解
HttpResponse 講解
HttpServletResponse概述:
在創(chuàng)建Servlet時(shí)會(huì)覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個(gè)參數(shù),一個(gè)為代表請(qǐng)求的request和代表響應(yīng)response。service方法中的response的類(lèi)型是ServletResponse,而doGet/doPost方法的response的類(lèi)型是HttpServletResponse,HttpServletResponse是ServletResponse的子接口,功能和方法更加強(qiáng)大。
Response運(yùn)行流程
響應(yīng)頭有很多這里只介紹常用的。
在瀏覽器可以按F12 抓包看響應(yīng)頭、請(qǐng)求頭、具體的可以再查。
設(shè)置響應(yīng)行
設(shè)置響應(yīng)的狀態(tài)碼
/** * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test3") public class HttpResponseTest3 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("設(shè)置狀態(tài)碼,前臺(tái)通過(guò)判斷狀態(tài)碼,來(lái)判斷請(qǐng)求是否成功"); resp.setStatus(404); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
測(cè)試
設(shè)置響應(yīng)頭
刷新 跳轉(zhuǎn)頁(yè)面
/** * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test4") public class HttpResponseTest4 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 設(shè)置響應(yīng)頭 每1秒自動(dòng)刷新 System.out.println("設(shè)置響應(yīng)頭 每1秒自動(dòng)刷新"); resp.setHeader("Refresh", "1"); //定時(shí)跳轉(zhuǎn) 3秒后將自動(dòng)跳轉(zhuǎn) // resp.setHeader("Refresh","3;URL=hello.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
測(cè)試
一個(gè)小demo 實(shí)現(xiàn)刷新 頁(yè)面累加
/** * response * @author Adimi */ @WebServlet("/test4") public class ResponseTest4 extends HttpServlet { private static Integer id=1; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Refresh","1"); PrintWriter writer = response.getWriter(); id++; writer.print("id==>"+id); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
設(shè)置字符編碼 解決中文亂碼問(wèn)題
/** * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test1") public class HttpResponseTest1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解決中文亂碼問(wèn)題 // 設(shè)置響應(yīng)頭 // 設(shè)置字符編碼 resp.setCharacterEncoding("UTF-8"); // 設(shè)置響應(yīng)內(nèi)容以什么格式展示到頁(yè)面 什么編碼格式 包含了設(shè)置字符編碼 resp.setContentType("text/html;charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.print("中國(guó),你好?。?!"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
測(cè)試
重定向 redirect
/** * 重定向 * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test5") public class HttpResponseTest5 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("hello.jsp"); // resp.setHeader("location","www.baidu.com"); 通過(guò)設(shè)置響應(yīng)頭轉(zhuǎn)發(fā) } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
request轉(zhuǎn)發(fā)
/** * 重定向 * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test5") public class HttpResponseTest5 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.sendRedirect("hello.jsp"); req.getRequestDispatcher("hello.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
重定向和轉(zhuǎn)發(fā)的區(qū)別
文件下載
獲取路徑資源
String path=this.getServletContext().getRealPath("WEB-INF\\classes\\8.jpg");
讀取資源
FileInputStream fileInputStream=new FileInputStream(path);
獲取到文件名,路徑在電腦上保存的形式是 \ \
String fileName=path.substring(path.lastIndexOf("\\")+1);
設(shè)置消息頭告訴瀏覽器,我要下載1.png這個(gè)圖片 設(shè)置編碼
resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
把讀取到的內(nèi)容回送給瀏覽器
int len=0; byte[] bytes=new byte[1024]; // ServletOutputStream 提供用于將二進(jìn)制數(shù)據(jù)發(fā)送到客戶(hù)端的輸出流 ServletOutputStream servletOutputStream=resp.getOutputStream(); while((len=fileInputStream.read(bytes))>0) { servletOutputStream.write(bytes,0,len); }
關(guān)閉資源
servletOutputStream.close(); fileInputStream.close();
注:8.jpg 放在我的resources 文件夾下 但是這里需要寫(xiě)的是編譯完8.jpg存放的位置
具體代碼
/** * @Author: crush * @Date: 2021-05-09 19:40 * version 1.0 */ @WebServlet("/down") public class ResponseDownFile extends HttpServlet { @Override protected 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); //設(shè)置消息頭告訴瀏覽器,我要下載1.png這個(gè)圖片 // 該方式文件名為中文時(shí)會(huì)亂碼 //防止中文亂碼 resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); //把讀取到的內(nèi)容回送給瀏覽器 int len=0; byte[] bytes=new byte[1024]; ServletOutputStream servletOutputStream=resp.getOutputStream(); while((len=fileInputStream.read(bytes))>0) { servletOutputStream.write(bytes,0,len); } // 關(guān)閉資源 servletOutputStream.close(); fileInputStream.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
HttpRequest 講解
HttpServletRequest概述
我們?cè)趧?chuàng)建Servlet時(shí)會(huì)覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個(gè)參數(shù),一個(gè)為代表請(qǐng)求的request和代表響應(yīng)response。service()方法中寫(xiě)了根據(jù)請(qǐng)求方式的不同調(diào)用doget()和dopost().
service方法中的request的類(lèi)型是ServletRequest,而doGet/doPost方法的request類(lèi)型HttpServletRequest,HttpServletRequest是ServletRequest的子接口,功能和方法更加強(qiáng)大.
Request 運(yùn)行流程
獲取請(qǐng)求攜帶的參數(shù)
/** * @Author: crush * @Date: 2021-05-11 16:52 * version 1.0 */ @WebServlet("/request1") public class RequestTest1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 這里是請(qǐng)求的參數(shù)名 必須是同名的 String username = req.getParameter("username"); String password = req.getParameter("password"); PrintWriter writer = resp.getWriter(); writer.print("<h1>"+username+":"+password+"</h1>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
獲取多個(gè)參數(shù)的值
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 設(shè)置請(qǐng)求的編碼 不然會(huì)亂碼 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)); } }
獲得請(qǐng)求行的信息
/** * @Author: crush * @Date: 2021-05-11 16:52 * version 1.0 */ @WebServlet("/request3") public class RequestTest3 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 獲得請(qǐng)求的url StringBuffer requestURL = req.getRequestURL(); System.out.println("請(qǐng)求的URL===>"+requestURL); // 獲得請(qǐng)求的Servlet的路徑 String path = req.getServletPath(); System.out.println("請(qǐng)求的Servlet的路徑===>"+path); //返回發(fā)出此請(qǐng)求的HTTP方法的名稱(chēng),例如GET,POST或PUT String method = req.getMethod(); System.out.println("返回發(fā)出此請(qǐng)求的HTTP方法的名稱(chēng)==>"+method); //返回發(fā)送請(qǐng)求的客戶(hù)端或最后一個(gè)代理的Internet協(xié)議(IP)地址 String remoteAddr = req.getRemoteAddr(); System.out.println("remoteAddr==>"+remoteAddr); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
request實(shí)現(xiàn)轉(zhuǎn)發(fā)
/** * @Author: crush * @Date: 2021-05-11 16:52 * version 1.0 */ @WebServlet("/request2") public class RequestTest2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 訪(fǎng)問(wèn)request2 轉(zhuǎn)發(fā)到 request4去 req.getRequestDispatcher("/request4").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
request是一個(gè)域?qū)ο?/h3>
request對(duì)象也是一個(gè)存儲(chǔ)數(shù)據(jù)的區(qū)域?qū)ο?,所以也具有如下方法?/p>
setAttribute(String name, Object o)
getAttribute(String name)
removeAttribute(String name)
ServletContext 作用域:
創(chuàng)建:?jiǎn)?dòng)web應(yīng)用程序的時(shí)候創(chuàng)建
銷(xiāo)毀:關(guān)閉web應(yīng)用程序的時(shí)候銷(xiāo)毀
域的作用范圍:整個(gè)web應(yīng)用的啟動(dòng)周期
request作用域:
創(chuàng)建:訪(fǎng)問(wèn)時(shí)創(chuàng)建request
銷(xiāo)毀:響應(yīng)結(jié)束request銷(xiāo)毀
域的作用范圍:一次請(qǐng)求中
總結(jié)
本篇文章就到這里了,希望能給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Java獲取項(xiàng)目路徑方式System.getProperty(“user.dir“)
這篇文章主要介紹了Java獲取項(xiàng)目路徑方式System.getProperty(“user.dir“),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12詳解BeanUtils.copyProperties()方法如何使用
這篇文章主要為大家介紹了詳解BeanUtils.copyProperties()方法如何使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07Java實(shí)現(xiàn)統(tǒng)計(jì)字符串出現(xiàn)的次數(shù)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)統(tǒng)計(jì)字符串出現(xiàn)的次數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10Mybatis mapper接口動(dòng)態(tài)代理開(kāi)發(fā)步驟解析
這篇文章主要介紹了Mybatis mapper接口動(dòng)態(tài)代理開(kāi)發(fā)步驟解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07話(huà)說(shuō)Spring Security權(quán)限管理(源碼詳解)
本篇文章主要介紹了話(huà)說(shuō)Spring Security權(quán)限管理(源碼詳解) ,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02SpringCloud讓微服務(wù)實(shí)現(xiàn)指定程序調(diào)用
這篇文章主要介紹了SpringCloud讓微服務(wù)實(shí)現(xiàn)指定程序調(diào)用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06SWT(JFace)體驗(yàn)之StyledText類(lèi)
有的時(shí)候Text需要實(shí)現(xiàn)這種那種的樣式。先提供在不使用StyledText類(lèi)的情況:2009-06-06java中int初始化可以為0,但不能為NULL問(wèn)題
這篇文章主要介紹了java中int初始化可以為0,但不能為NULL問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02idea復(fù)制module(項(xiàng)目)并在一個(gè)窗口展示的教程詳解
這篇文章主要介紹了idea復(fù)制module(項(xiàng)目)并在一個(gè)窗口展示的方法,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06