您好,登錄后才能下訂單哦!
JavaWeb中HttpResponse和HttpRequest如何使用,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
在創建Servlet時會覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個參數,一個為代表請求的request和代表響應response。service方法中的response的類型是ServletResponse,而doGet/doPost方法的response的類型是HttpServletResponse,HttpServletResponse是ServletResponse的子接口,功能和方法更加強大。
響應頭有很多這里只介紹常用的。
在瀏覽器可以按F12 抓包看響應頭、請求頭、具體的可以再查。
設置響應的狀態碼
/** * @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("設置狀態碼,前臺通過判斷狀態碼,來判斷請求是否成功"); resp.setStatus(404); } @Override protected 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 { @Override protected 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"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
測試
/** * 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); } }
/** * @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 { // 解決中文亂碼問題 // 設置響應頭 // 設置字符編碼 resp.setCharacterEncoding("UTF-8"); // 設置響應內容以什么格式展示到頁面 什么編碼格式 包含了設置字符編碼 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); } }
測試
/** * 重定向 * @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"); 通過設置響應頭轉發 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
/** * 重定向 * @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); } }
獲取路徑資源
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); }
關閉資源
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); //設置消息頭告訴瀏覽器,我要下載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(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
我們在創建Servlet時會覆蓋service()方法,或doGet()/doPost(),這些方法都有兩個參數,一個為代表請求的request和代表響應response。service()方法中寫了根據請求方式的不同調用doget()和dopost().
service方法中的request的類型是ServletRequest,而doGet/doPost方法的request類型HttpServletRequest,HttpServletRequest是ServletRequest的子接口,功能和方法更加強大.
/** * @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 { // 這里是請求的參數名 必須是同名的 String username = req.getParameter("username"); String password = req.getParameter("password"); PrintWriter writer = resp.getWriter(); writer.print("<h2>"+username+":"+password+"</h2>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
@Override protected 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 { @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); //返回發出此請求的HTTP方法的名稱,例如GET,POST或PUT String method = req.getMethod(); System.out.println("返回發出此請求的HTTP方法的名稱==>"+method); //返回發送請求的客戶端或最后一個代理的Internet協議(IP)地址 String remoteAddr = req.getRemoteAddr(); System.out.println("remoteAddr==>"+remoteAddr); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
/** * @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 轉發到 request4去 req.getRequestDispatcher("/request4").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
request對象也是一個存儲數據的區域對象,所以也具有如下方法:
setAttribute(String name, Object o)
getAttribute(String name)
removeAttribute(String name)
創建:啟動web應用程序的時候創建
銷毀:關閉web應用程序的時候銷毀
域的作用范圍:整個web應用的啟動周期
創建:訪問時創建request
銷毀:響應結束request銷毀
域的作用范圍:一次請求中
關于JavaWeb中HttpResponse和HttpRequest如何使用問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。