request 对象和 response 对象
Web服務器收到客戶端的http請求,會針對每一次請求,分別創建一個用于代表請求的request對象、和代表響應的response對象
HttpServletResponse
HttpServletResponse對象代表服務器的響應。這個對象中封裝了向客戶端發送數據、發送響應頭,發送響應狀態碼的方法。
1.向客戶端輸出中文數據(字節)
package cn.lsl.response;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test5(response); } //輸出整數:最好轉換成字符串輸出 private void test5(HttpServletResponse response) throws IOException{ int i = 98; response.getOutputStream().write((i+"").getBytes()); } //以字節流用默認編碼向客戶端輸出中文數據:沒有亂碼 //默認的是GBK private void test1(HttpServletResponse response) throws IOException{ String s = "你好!一"; ServletOutputStream out = response.getOutputStream(); out.write(s.getBytes()); } //以字節流用utf-8編碼向客戶端輸出中文數據 //以UTF-8編碼發送數據,瀏覽器(默認用GB2312)會出現亂碼 private void test2(HttpServletResponse response) throws IOException{ String s = "你好!二"; //通知客戶端查看UTF-8碼表 response.setHeader("Content-Type", "text/html;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); out.write(s.getBytes("UTF-8")); } //以字節流用utf-8編碼向客戶端輸出中文數據 private void test3(HttpServletResponse response) throws IOException{ String s = "你好!三"; ServletOutputStream out = response.getOutputStream(); out.write("<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>".getBytes("UTF-8")); out.write(s.getBytes("UTF-8")); } //以字節流用utf-8編碼向客戶端輸出中文數據 private void test4(HttpServletResponse response) throws IOException{ String s = "你好!四"; response.setContentType("text/html;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); out.write(s.getBytes("UTF-8")); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 分析:出現亂碼的圖解
?
解決辦法:
1)通過更改瀏覽器的編碼方式:IE/”查看”/”編碼”/”UTF-8”(不可取)
2)通過設置響應頭告知客戶端編碼方式:response.setHeader(“Content-type”, “text/html;charset=UTF-8”);//告知瀏覽器數據類型及編碼
3)通過meta標簽模擬請求頭:out.write("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />".getBytes());
4)通過以下方法:response.setContentType("text/html;charset=UTF-8");
2.向客戶端輸出中文數據(字符)
package cn.lsl.response;import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test3(response); } //字符流輸出中文數據 private void test1(HttpServletResponse response) throws IOException{ String s = "你好!一"; response.setCharacterEncoding("UTF-8"); //設置查的UTF-8(對內容進行編碼,查utf-8) response.setHeader("Content-Type", "text/html;charset=UTF-8");//通知瀏覽器以utf-8打開 PrintWriter out = response.getWriter(); out.write(s);//默認查的是ISO-8859-1碼表 } //字符流輸出中文數據 private void test2(HttpServletResponse response) throws IOException{ String s = "你好!二"; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write(s); } //字符流輸出中文數據 private void test3(HttpServletResponse response) throws IOException{ String s = "你好!三"; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write(s); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 分析:
亂碼原因:以默認編碼發送數據 ISO-8859-1(沒有中國二字編碼),此時會發生亂碼
解決辦法:
1)
setCharacterEncoding(“UTF-8”);//更改編碼為UTF-8
response.setHead(“Context-type”,”text/html;charset=UTF-8”);//告訴客戶端編碼方式
2)response.setContentType("text/html;charset=utf-8");
在字符流輸出中文數據時:
response.setContentType("text/html;charset=utf-8");有兩個作用:
通知字符流以UTF-8編碼輸出
通知客戶端以UTF-8解碼顯示
3.輸出隨機驗證碼
package cn.lsl.response;import java.awt.Color;
import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //通知瀏覽器不要緩存 response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); int width = 120; int height = 25; //創建一副內存圖像BufferedImage BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //得到屬于該圖片的畫筆:Graphics(); Graphics g = image.getGraphics(); //畫邊框 g.setColor(Color.BLUE); g.drawRect(0, 0, width, height); //填充背景色 g.setColor(Color.YELLOW); g.fillRect(1, 1, width-2, height-2); //畫干擾線 g.setColor(Color.GRAY); Random r = new Random(); for(int i=0; i<10; i++) g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height)); //隨機數字 g.setColor(Color.RED); g.setFont(new Font("宋體",Font.BOLD|Font.ITALIC,20)); int x = 23; for(int i=0; i<4; i++){ g.drawString(r.nextInt(10)+"", x, 20); x = x+20; } //輸出到瀏覽器的頁面上:ImageIO ImageIO.write(image, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 4.定時刷新
package cn.lsl.response;import java.io.IOException;
import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test2(response); } //定時刷新到自己 private void test1(HttpServletResponse response) throws IOException{ Random r = new Random(); int i = r.nextInt(); response.setIntHeader("Refresh", 1); response.getOutputStream().write((i+"").getBytes()); } //刷到別的頁面 private void test2(HttpServletResponse response) throws IOException{ response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); response.setHeader("Refresh", "2;URL=/Response/index.jsp"); out.write("登陸成功!2秒后將跳轉到主頁!若沒有跳轉,請猛點<a href='/Response/index.jsp'>這里</a>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 5.控制緩存時間
package cn.lsl.response;import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //緩存一小時 response.setDateHeader("Expires", System.currentTimeMillis()+60*60*1000); response.getWriter().write("hello"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 6.請求重定向
請求重定向:一個web資源收到客戶端請求后,通知客戶端去訪問另外一個web資源,這稱之???????? 為請求重定向。
地址欄會連,并發送2次請求,增加服務器負擔。
實現方式:response.sendRedirect();
原理:302/307狀態碼和location頭即可實現重定向
package cn.lsl.response;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResponseDemo6 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setStatus(302); // response.setHeader("Location", "/Response/index.jsp"); response.sendRedirect("/Response/index.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 7.getOutputStream和getWriter方法分別用于得到輸出二進制數據、輸出文本數據的ServletOuputStream、Printwriter對象。
getOutputStream和getWriter這兩個方法互相排斥,調用了其中的任何一個方法后,就不能再調用另一方法。會拋異常。
異常為:getOutputStream() has already been called for this response
package cn.lsl.response;import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //字節流和字符流同時使用,報錯 //getOutputStream() has already been called for this response public class ResponseDemo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String s1 = "a"; response.getOutputStream().write(s1.getBytes()); String s2 = "b"; response.getWriter().write(s2); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 注:通過字符流或字節流輸出的數據并不是直接打給瀏覽器的。而是把數據寫到response對象的緩存中的。服務器從緩存中取出數據,按照HTTP協議的響應格式輸出給瀏覽器。如果你調用的response的輸出流沒有主動關閉,服務器會替你關的。
?
HttpServletRequest
HttpServletRequest對象代表客戶端的請求,當客戶端通過HTTP協議訪問服務器時,HTTP請求頭中的所有信息都封裝在這個對象中,通過這個對象的方法,可以獲得客戶這些信息。
1.獲取客戶機信息的方法
getRequestURL方法返回客戶端發出請求時的完整URL。
getRequestURI方法返回請求行中的資源名部分。
getQueryString 方法返回請求行中的參數部分。
getRemoteAddr方法返回發出請求的客戶機的IP地址
getRemoteHost方法返回發出請求的客戶機的完整主機名
getRemotePort方法返回客戶機所使用的網絡端口號
getLocalAddr方法返回WEB服務器的IP地址。
getLocalName方法返回WEB服務器的主機名
getMethod得到客戶機請求方式
eg:
package cn.lsl.request;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //獲取客戶機信息 public class RequestDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取URL和URI //url:http://localhost:8080/Request/servlet/RequestDemo1 //uri:/Request/servlet/RequestDemo1 System.out.println("url:"+request.getRequestURL()); System.out.println("uri:"+request.getRequestURI()); //通過getQueryString可以獲得get方式提交查詢串url中?后面部分 System.out.println("queryString:"+request.getQueryString()); //獲得客戶端ip System.out.println("ip:"+request.getRemoteAddr()); //通過getContextPath獲得工程虛擬目錄名稱 System.out.println("工程虛擬目錄名稱:"+request.getContextPath()); //通過getMethod獲得請求方式 System.out.println("請求方式:"+request.getMethod()); //獲得當前訪問資源路徑 ----/servlet/RequestDemo1 System.out.println("當前訪問資源路徑:"+request.getRequestURI().substring(request.getContextPath().length())); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 注:
1)URL和URI的區別
URL: http://localhost:8080/Request/servlet/RequestDemo1
URI: /Request/servlet/RequestDemo1
URI 包含 URL的 ,URL 一定完成路徑,URI可以相對路徑
http://localhost:8080/Request/servlet/RequestDemo1
是一個URL 同時也是 URI
/Request/servlet/RequestDemo1 ---- 都是URI 不是URL
2)獲得當前訪問資源路徑 :
request.getRequestURI().substring(request.getContextPath().length());
2.獲取請求頭信息
getHeader 獲得頭信息的值,轉換一個字符串
getHeaders 獲得頭信息值 ,獲得Enumeration
getHeaderNames 獲得所有頭信息名稱? 返回 Enumeration
eg:
package cn.lsl.request;import java.io.IOException;
import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取指定頭信息字段 String value = request.getHeader("Accept-Encoding"); System.out.println(value); System.out.println("---------------"); //獲得所有頭信息內容 Enumeration<String> enumeration = request.getHeaderNames(); while(enumeration.hasMoreElements()){ String name = enumeration.nextElement(); System.out.println(name+":"+request.getHeader(name)); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 3.防盜鏈程序
referer.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> <head> <title>referer.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <h1>通過鏈接訪問RequestDemo3 不是盜鏈</h1> <a href="/Request/servlet/RequestDemo3">link</a> </body> </html> package cn.lsl.request;import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestDemo3 extends HttpServlet { //防盜鏈 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //通過getHeader獲得referer頭信息 String referer = request.getHeader("referer"); //判斷頭信息可以知道是不是盜鏈 response.setContentType("text/html;charset=utf-8"); if(referer == null || !referer.startsWith("http://localhost")){ //盜鏈 response.getWriter().println("是盜鏈"); }else{ //不是盜鏈 response.getWriter().println("真不是盜鏈"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 4.獲取客戶機請求參數
常用API四個
getParameter
getParameterValues
getParameterNames
getParameterMap
eg:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> <head> <title>request.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <h1>分別以get和post方式提交數據</h1> <h1>第一種:通過超鏈接提交數據以?方式</h1> <a href="/Request/servlet/RequestDemo4?name=zhangsan&city=shenzhen">超鏈接提交數據</a> <h1>第二種:通過form的post方式提交數據</h1> <form action="/Request/servlet/RequestDemo4" method="post"> 姓名<input type="text" name="name" /><br/> 城市<input type="text" name="city" /><br/> <input type="submit" value="提交"> </form> </body> </html> package cn.lsl.request;import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); System.out.println(name); String city = request.getParameter("city"); System.out.println(city); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 5.獲取復雜表單的數據及解決中文亂碼問題
regist.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> <head> <title>regist.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="/Request/servlet/RequestDemo5" method="post"> <table> <tr> <td> 用戶名 </td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td> 密碼 </td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td> 性別 </td> <td> <input type="radio" name="gender" value="male" /> 男 <input type="radio" name="gender" value="female" /> 女 </td> </tr> <tr> <td> 愛好 </td> <td> <input type="checkbox" name="hobby" value="sport" /> 運動 <input type="checkbox" name="hobby" value="music" /> 音樂 <input type="checkbox" name="hobby" value="game" /> 游戲 </td> </tr> <tr> <td> 城市 </td> <td> <select name="city"> <option value="beijing"> 北京 </option> <option value="shanghai"> 上海 </option> <option value="shenzhen"> 深圳 </option> </select> </td> </
轉載于:https://www.cnblogs.com/wl0000-03/p/6098552.html
總結
以上是生活随笔為你收集整理的request 对象和 response 对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 会有人交易吗100分求解要详细给价有人交
- 下一篇: PYTHON学习笔记-DAY-16