1. 程式人生 > >request和response總結

request和response總結

request和response是什麼?
request是請求,在瀏覽器輸入地址,回車,就是一個請求
response是響應,伺服器根據請求,返回資料到瀏覽器顯示,就是一個響應


第一,response
1 HttpServletResponse是一個子介面,ServletResponse是父介面,是伺服器響應物件
2 http分為三個部分
1.響應行
設定狀態碼 setStatus(int sc)
response.setStatus(302);


2.響應頭
是key-value結構,一個key對應一個value,可以一個key對應多個value
(常用)設定響應頭setHeader(String name , String value);一個key對應一個value
響應名稱響應引數
setHeader("aa","11");
setHeader("aa","22");
結果是 aa  :  22
setIntHeader(String name ,int value)
setDateHeader(String name ,long date)毫秒值


針對是addHeader(String name ,int value)一個key對應多個value
addHeader("bb","55");
addHeader("bb","66");
結果是bb  : 55,66


addIntHeader(String name ,int value)
addDateHeader(String name ,long date)毫秒值


3.響應體
向頁面顯示內容
getWriter() 字元流輸出
getOutputStream()位元組流輸出


第二,重定向
使用重定向實現登入操作
1.需求
在登入頁面中,輸入使用者名稱和密碼,判斷輸入的使用者和密碼是否正確
如果使用者名稱和密碼都正確,登入成功,向頁面輸出內容
如果使用者名稱或者密碼有一個是錯誤的,重定向(2次請求,2次響應)到登入頁面

2.步驟
第一步:建立登入頁面,寫表單,在表單裡面寫兩個輸入項,一個輸入使用者名稱,一個輸入密碼,
提交到一個servlet裡面

第二步:建立servlet,在這個servlet裡面首先獲取到輸入的使用者名稱和密碼,
根據使用者名稱和密碼進行判斷(使用者名稱如果是admin,密碼如果是123456表示正確的)

如果使用者名稱和密碼都正確,登入成功,向頁面輸出內容;
response.getWriter().write("login success");

否則重定向到登入頁面

重定向的程式碼簡寫的方式
response.sendRedirect("要重定向到的頁面的路徑");

String login = request.getParameter("login");
String password = request.getParameter("password");

if ("admin".equals(login) && "123456".equals(password)) {
response.getWriter().write("login success");
} else {//重定向
/*response.setStatus(302);
response.setHeader("Location", "http://localhost:8080/day08_my/html/demo02_other.html");
*/
response.sendRedirect("http://localhost:8080/day08_my/html/demo02_other.html");
}


第三,定時跳轉
當註冊一個網站,註冊完成之後,5秒之後跳轉到登入頁面


3.2 實現方式
(1)使用頭資訊Refresh實現
(2)寫法: response.setHeader("Refresh","在幾秒值後跳轉;url=要跳轉到頁面的路徑");
3.3 建立servlet,在servlet實現,在五秒之後跳轉到一個頁面
response.setHeader("Refresh", "3;url=http://localhost:8080/day08_my/html/demo02.html");


如:後臺解決
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setHeader("Refresh", "3;url=http://localhost:8080/day08_my/html/demo02.html");

response.setContentType("text/html; charset=UTF-8");
response.getWriter().write("Demo03Servlet---3秒之後跳轉");
}


前臺解決
<html>
<head>
<meta http-equiv="Refresh" content="3;url=http://localhost:8080/day08_my/html/demo02.html">
</head>
  
 <body>
 <h1>Demo03.html---3秒之後跳轉</h1>
 </body>
</html>


倒計時
<!DOCTYPE html>
<html>
 <head>
<title>demo03.html</title>
<meta http-equiv="Refresh" content="3;url=http://localhost:8080/day08_my/html/demo02.html">
 </head>
 <!--3秒之後跳轉-->
 
 <body>
 <h1>Demo03.html---<span id="spanid">3</span>秒之後跳轉</h1>
 </body>
 
 <script type="text/javascript">
 //顯示3,2,1,...倒數
var time=2;
function loadTime(){
var span = document.getElementById("spanid");
span.innerHTML=time--;
}
setInterval("loadTime()", "1000");
 </script>
</html>


第四,設定響應體
1 使用位元組流向頁面輸出
* 1、設定瀏覽器的編碼
* 2、設定位元組陣列的編碼
* 讓瀏覽器的編碼和位元組陣列的編碼一致


//<meta http-equiv="content-type" content="text/html; charset=UTF-8">
response.setHeader("content-type", "text/html; charset=UTF-8");
response.getOutputStream().write("4.1 使用位元組流向頁面輸出內容".getBytes("UTF-8"));

2 使用字元流向頁面輸出


* 解決方法:
* 1、設定response緩衝區的編碼
* 2、設定瀏覽器的編碼
* response緩衝區的編碼和瀏覽器的編碼一致


response.setCharacterEncoding("UTF-8");
//<meta http-equiv="content-type" content="text/html; charset=UTF-8">
response.setHeader("content-type", "text/html; charset=UTF-8");
response.getWriter().write("4.2 使用字元流向頁面輸出內容");


第五,流的注意事項
5.1 字元流向頁面輸出中文亂碼問題解決,簡寫方式
//<meta http-equiv="content-type" content="text/html; charset=UTF-8">
reesponse.setContentType("text/html; charset=UTF-8");
response.getWriter().write("4.2 ,簡寫 ,使用字元流向頁面輸出內容");


5.2 位元組流和字元流是互斥的

5.3 使用字元流不能直接向頁面輸出數字
//根據數字到碼錶中查詢數字對應的字元,把字元輸出
response.setCharacterEncoding("utf-8");
response.getWriter().write(111);


第六,驗證碼的案例
第一步:生成圖片
第二步:生成隨機的數字和字母
第三步:把數字和字母畫到圖片上
第四步:把圖片顯示到頁面上


/*
* 程式碼實現驗證碼
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//生成圖片
int width = 150;
int height = 60;
BufferedImage bufferedImage =
new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
//得到畫筆
Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
//生成四個隨機的數字和字母
String words = "asdfghjklqwertyuiopzxcvbASDFGHJKLQWERTYUIOPZXCVB1234567890";
//建立Random物件
Random r = new Random();
int x = 25;
int y = 25;
//設定顏色
g2d.setColor(Color.YELLOW);
//設定字型的樣式
g2d.setFont(new Font("宋體",Font.BOLD,25));
//rotate(double theta, double x, double y) 
//弧度=角度*3.14/180
for(int i=1;i<=4;i++) {
int idx = r.nextInt(words.length());
//根據位置得到具體的字元
char ch = words.charAt(idx);

//旋轉+- 30度
int jiaodu = r.nextInt(60)-30;
double hudu = jiaodu*Math.PI/180;
//旋轉的效果
g2d.rotate(hudu, x, y);
//把字元畫到圖片上
g2d.drawString(ch+"", x, y);

x += 25;

//轉回去
g2d.rotate(-hudu, x, y);
}
//生成三條幹擾線
g2d.setColor(Color.green);
int x1,y1,x2,y2;
for(int m=1;m<=3;m++) {
x1 = r.nextInt(width);
y1 = r.nextInt(height);

x2 = r.nextInt(width);
y2 = r.nextInt(height);
g2d.drawLine(x1, y1, x2, y2);
}
//把圖片顯示到頁面上
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}

<!--頁面顯示驗證碼-->
<body>
    <form name="f1" id="f1" action="" method="post">
      <table border="0">
        <tr>
          <td>Login:</td>
          <td><input type="text" name="login" id="login"></td>
        </tr>
        <tr>
          <td>Password:</td>
          <td><input type="password" name="password" id="password"></td>
        </tr> 
        <tr>
        <tr>
          <td>code:</td>
          <td><img src="http://localhost:8080/day08_my/demo06" id="img1" onclick="loadCode();"/></td>
        </tr> 
        <tr>
          <td colspan="2" align="center"><input type="submit"></td>
        </tr>
      </table>
    </form>
  </body>
  <script type="text/javascript">
  function loadCode(){
  var img1 = document.getElementById("img1");
//這裡"/day08_my/demo06"瀏覽器有快取,所有需要加一個變數,時間物件是瀏覽器物件
  img1.src="/day08_my/demo06?time="+new Date().getTime();
  }
  </script>




第七,檔案的下載
/*
7.1 檔案下載的基本實現的步驟
(0)設定頭資訊 Content-Disposition,無論是什麼格式的檔案都以下載方式開啟
(1)在伺服器上面有一個可以下載的檔案
(2)從伺服器上拿到這個檔案(使用檔案輸入流得到檔案)
(3)使用輸出流把檔案寫到瀏覽器
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//輸入關聯下載的資源

String path = "/download/a.zip";
InputStream is = getServletContext().getResourceAsStream(path);

int lastIndexOf = path.lastIndexOf("/");
String filename = path.substring(lastIndexOf+1);

response.setHeader("Content-Disposition", "attachment;filename="+filename);

OutputStream os = response.getOutputStream();

int len = 0;
byte[] b = new byte[8192];
while ((len=is.read(b))!=-1) {
os.write(b, 0, len);
}
is.close();
os.close();
}


第八,request物件
/*
* (1)getMethod() :得到http請求方式
(2)getRequestURI() :得到請求地址(不包含ip+埠號)
(3)getProtocol() :得到http的版本
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//瀏覽器中 http://localhost:8080/day08_my/rdemo01
// GET
System.out.println(request.getMethod());


// day08_my/rdemo01
System.out.println(request.getRequestURI());


// HTTP/1.1
System.out.println(request.getProtocol());


}


/*
* 8.3 獲取請求頭的資訊
(1)getHeader(java.lang.String name) :根據名稱得到請求頭的值
= 頭資訊 User-Agent:獲取當前請求的瀏覽器的型別
= String agent = request.getHeader("User-Agent");
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0
System.out.println(request.getHeader("User-Agent"));
}

/*
* 8.4 獲取客戶機的資訊
(1)getContextPath() :請求專案的名稱
(2)getRequestURL() :客戶端傳送的請求的路徑
(3)getRemoteAddr() :獲取當前客戶端的ip地址
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 瀏覽器中 http://localhost:8080/day08_my/rdemo02
// day08_my
System.out.println(request.getContextPath());


// http://localhost:8080/day08_my/rdemo02
System.out.println(request.getRequestURL());


// 0:0:0:0:0:0:0:1
System.out.println(request.getRemoteAddr());


}


<form name="f1" id="f1" action="http://localhost:8080/day08_my/rdemo04" method="post">
      <table border="0">
        <tr>
          <td>Login:</td>
          <td><input type="text" name="login" id="login"></td>
        </tr>
        <tr>
          <td>Password:</td>
          <td><input type="password" name="password" id="password"></td>
        </tr> 
         <tr>
          <td>love:</td>
          <td>
          <input type="checkbox" id="" name="love" value="lanqiu"/>籃球
<input type="checkbox" id="" name="love" value="pingpang"/>乒乓球
<input type="checkbox" id="" name="love" value="yumao"/>羽毛球</td>
        </tr> 
        <tr>
          <td colspan="2" align="center"><input type="submit"></td>
        </tr>
      </table>
    </form>
//(1)String getParameter(java.lang.String name) :引數是表單輸入項name屬性的值,根據名稱得到輸入的值
private void test1(HttpServletRequest request) {
String login = request.getParameter("login");
String password = request.getParameter("password");
System.out.println(login);
System.out.println(password);
}
//(2)String[] getParameterValues(java.lang.String name) :引數是表單輸入項name的值,針對複選框的情況
private void test2(HttpServletRequest request) {
String[] loves = request.getParameterValues("love");
System.out.println(Arrays.toString(loves));
}
//(3)Map<java.lang.String,java.lang.String[]> getParameterMap() :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取所有的name和value
Map<String, String[]> map = request.getParameterMap();
Set<Entry<String, String[]>> ens = map.entrySet();
for (Entry<String, String[]> en : ens) {
String key = en.getKey();
String[] val = en.getValue();
System.out.println(key+"..."+Arrays.toString(val));
}
}


request中表單提交的中文資料亂碼問題的解決
(1)post提交方式解決方法,會有一個緩衝區
/*
* (1)post提交方式解決方法
*/
//方法一
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String decode = URLDecoder.decode(request.getParameter("name"), "UTF-8");
System.out.println(decode);
}

//方法二
private void test1(HttpServletRequest request)
throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");//會有一個緩衝區
System.out.println(request.getParameter("login"));
System.out.println(request.getParameter("password"));
}


(2)get提交中文亂碼解決
改tomcat伺服器
   <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="utf-8"/>


/*
*(2)get提交中文亂碼解決
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String login = request.getParameter("login");
login = new String(login.getBytes("iso8859-1"),"utf-8");
System.out.println(login);
}


request是域物件:在一定的範圍內,可以存值和取值
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("name", "張三");
//轉發
//request.getRequestDispatcher("/rdemo08").forward(request, response);
//重定向
response.sendRedirect("/day08_my/rdemo08");
}


/*
*獲取request域裡面設定的那個值
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = (String) request.getAttribute("name");
System.out.println(name);
}

重定向和轉發的區別
第一,重定向程式碼是 response.sendRedirect("");
說明是伺服器端的方法
2次請求,2次響應,路徑是有專案名稱的
域物件用session來儲存資料


第二,轉發程式碼是 request.getRequestDispatcher("").forward(request, response);
說明是伺服器端的方法
1次請求,1次響應,路徑是不包含專案名稱
域物件用request來儲存資料


重定向:從一個網站到另一個網站
轉發:請求的過程中需要攜帶資料


第九,使用request域物件+轉發實現登入功能
(1)建立登入頁面,在登入頁面中寫表單,提交到servlet裡面
(2)建立servlet,在servlet裡面獲取表單提交的資料,判斷使用者名稱和密碼是否正確
(3)如果使用者名稱和密碼都正確,表示登入成功,向頁面輸出內容
(4)如果使用者名稱或者密碼錯誤,表示登入失敗,轉發到登入頁面(同時向頁面顯示錯誤資訊)
= 轉發的程式碼:request.getRequestDispatcher("登入的頁面 不帶專案名稱").forward(request, response);
= 傳遞資料的頁面:首先把顯示內容放到request域裡面,使用轉發到登入頁面,在登入頁面中使用el表示式獲取
request域裡面的值
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
<base href="<%=basePath%>">

<title>My JSP 'MyJsp.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


 </head>
 
 <body>
<form name="f1" id="f1" action="/day08_my/reqDemo09" method="post">
 <table border="0">
<tr>
 <td>Login:</td>
 <td><input type="text" name="login" id="login"></td>
</tr>
<tr>
 <td>Password:</td>
 <td><input type="password" name="password" id="password"></td>
</tr> 
<tr>
 <td colspan="2" align="center"><input type="submit"></td>
</tr>
 </table>
</form>

<!-- 傳遞資料的頁面:
首先把顯示內容放到request域裡面,使用轉發到登入頁面,
在登入頁面中使用el表示式獲取request域裡面的值
-->
${msg}<br/>
 </body>
</html>


public class ReqDemo09 extends HttpServlet {
/*
*9、轉發的案例
9.1 使用request域物件+轉發實現登入功能

(1)建立登入頁面,在登入頁面中寫表單,提交到servlet裡面
(2)建立servlet,在servlet裡面獲取表單提交的資料,判斷使用者名稱和密碼是否正確
(3)如果使用者名稱和密碼都正確,表示登入成功,向頁面輸出內容
(4)如果使用者名稱或者密碼錯誤,表示登入失敗,轉發到登入頁面(同時向頁面顯示錯誤資訊)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取表單提交的資料
String login = request.getParameter("login");
String password = request.getParameter("password");
//判斷使用者名稱和密碼
if ("admin".equals(login) && "123456".equals(password)) {
//如果使用者名稱和密碼都正確,表示登入成功,向頁面輸出內容
response.setContentType("text/html; charset=UTF-8");
response.getWriter().write("登入成功");
}else{
//使用者名稱或者密碼錯誤,表示登入失敗,轉發到登入頁面(同時向頁面顯示錯誤資訊)
request.setAttribute("msg", "使用者名稱或密碼錯誤");
request.getRequestDispatcher("/html/rdemo09.jsp").forward(request, response);
}

}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}


}