JavaWeb入門:HttpResponse和HttpRequest詳解
HttpResponse 講解
HttpServletResponse概述:
在創(chuàng)建Servlet時會覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個參數(shù),一個為代表請求的request和代表響應(yīng)response。service方法中的response的類型是ServletResponse,而doGet/doPost方法的response的類型是HttpServletResponse,HttpServletResponse是ServletResponse的子接口,功能和方法更加強(qiáng)大。
Response運(yùn)行流程

響應(yīng)頭有很多這里只介紹常用的。
![[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-bAvaDBGw-1620739367741)(C:\Users\ASUS\Desktop\JavaWeb_study\JavaWeb\JavaWeb.assets\image-20210511163256716.png)]](http://img.jbzj.com/file_images/article/202107/2021071616193781.jpg)
在瀏覽器可以按F12 抓包看響應(yī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)碼,來判斷請求是否成功");
resp.setStatus(404);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
測試

設(shè)置響應(yīng)頭
刷新 跳轉(zhuǎn)頁面
/**
* @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秒自動刷新
System.out.println("設(shè)置響應(yīng)頭 每1秒自動刷新");
resp.setHeader("Refresh", "1");
//定時跳轉(zhuǎn) 3秒后將自動跳轉(zhuǎn)
// resp.setHeader("Refresh","3;URL=hello.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
測試
![[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-LGJQhKor-1620739367743)(C:\Users\ASUS\Desktop\JavaWeb_study\JavaWeb\JavaWeb.assets\image-20210511162434487.png)]](http://img.jbzj.com/file_images/article/202107/2021071616193783.png)
一個小demo 實(shí)現(xiàn)刷新 頁面累加
/**
* 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è)置字符編碼 解決中文亂碼問題
/**
* @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 {
// 解決中文亂碼問題
// 設(shè)置響應(yīng)頭
// 設(shè)置字符編碼 resp.setCharacterEncoding("UTF-8");
// 設(shè)置響應(yīng)內(nèi)容以什么格式展示到頁面 什么編碼格式 包含了設(shè)置字符編碼
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.print("中國,你好?。?!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
測試
![[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-5VCR2LeF-1620739367746)(C:\Users\ASUS\Desktop\JavaWeb_study\JavaWeb\JavaWeb.assets\image-20210511162823603.png)]](http://img.jbzj.com/file_images/article/202107/2021071616193784.png)
重定向 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"); 通過設(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這個圖片 設(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ā)送到客戶端的輸出流
ServletOutputStream servletOutputStream=resp.getOutputStream();
while((len=fileInputStream.read(bytes))>0) {
servletOutputStream.write(bytes,0,len);
}
關(guān)閉資源
servletOutputStream.close();
fileInputStream.close();
注:8.jpg 放在我的resources 文件夾下 但是這里需要寫的是編譯完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這個圖片
// 該方式文件名為中文時會亂碼
//防止中文亂碼
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概述
我們在創(chuàng)建Servlet時會覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個參數(shù),一個為代表請求的request和代表響應(yīng)response。service()方法中寫了根據(jù)請求方式的不同調(diào)用doget()和dopost().
service方法中的request的類型是ServletRequest,而doGet/doPost方法的request類型HttpServletRequest,HttpServletRequest是ServletRequest的子接口,功能和方法更加強(qiáng)大.
Request 運(yùn)行流程

獲取請求攜帶的參數(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 {
// 這里是請求的參數(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);
}
}
![[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-2zxGslkb-1620739367750)(C:\Users\ASUS\Desktop\JavaWeb_study\JavaWeb\JavaWeb.assets\image-20210511170056042.png)]](http://img.jbzj.com/file_images/article/202107/2021071616193887.png)
獲取多個參數(shù)的值
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 設(shè)置請求的編碼 不然會亂碼
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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 獲得請求的url
StringBuffer requestURL = req.getRequestURL();
System.out.println("請求的URL===>"+requestURL);
// 獲得請求的Servlet的路徑
String path = req.getServletPath();
System.out.println("請求的Servlet的路徑===>"+path);
//返回發(fā)出此請求的HTTP方法的名稱,例如GET,POST或PUT
String method = req.getMethod();
System.out.println("返回發(fā)出此請求的HTTP方法的名稱==>"+method);
//返回發(fā)送請求的客戶端或最后一個代理的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 {
// 訪問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是一個域?qū)ο?/h3>
request對象也是一個存儲數(shù)據(jù)的區(qū)域?qū)ο?,所以也具有如下方法?/p>
setAttribute(String name, Object o)
getAttribute(String name)
removeAttribute(String name)
ServletContext 作用域:
創(chuàng)建:啟動web應(yīng)用程序的時候創(chuàng)建
銷毀:關(guān)閉web應(yīng)用程序的時候銷毀
域的作用范圍:整個web應(yīng)用的啟動周期
request作用域:
創(chuàng)建:訪問時創(chuàng)建request
銷毀:響應(yīng)結(jié)束request銷毀
域的作用范圍:一次請求中
總結(jié)
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Java獲取項(xiàng)目路徑方式System.getProperty(“user.dir“)
這篇文章主要介紹了Java獲取項(xiàng)目路徑方式System.getProperty(“user.dir“),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
詳解BeanUtils.copyProperties()方法如何使用
這篇文章主要為大家介紹了詳解BeanUtils.copyProperties()方法如何使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
Java實(shí)現(xiàn)統(tǒng)計字符串出現(xiàn)的次數(shù)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)統(tǒng)計字符串出現(xiàn)的次數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10
Mybatis mapper接口動態(tài)代理開發(fā)步驟解析
這篇文章主要介紹了Mybatis mapper接口動態(tài)代理開發(fā)步驟解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07
話說Spring Security權(quán)限管理(源碼詳解)
本篇文章主要介紹了話說Spring Security權(quán)限管理(源碼詳解) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
SpringCloud讓微服務(wù)實(shí)現(xiàn)指定程序調(diào)用
這篇文章主要介紹了SpringCloud讓微服務(wù)實(shí)現(xiàn)指定程序調(diào)用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
idea復(fù)制module(項(xiàng)目)并在一個窗口展示的教程詳解
這篇文章主要介紹了idea復(fù)制module(項(xiàng)目)并在一個窗口展示的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06

