標籤:style blog color io os 使用 ar java for
1、response
屬於重新導向請求;
其地址欄的URL會改變;
會向伺服器發送兩次請求;
2、 request
屬於請求轉寄;
其地址欄的URL不會改變;
向伺服器發送一次請求;
舉一個區分它們的簡單一實例:
A向B借錢:
第一種:用response。B沒有錢,請求失敗,但是B告訴A,C有錢。於是A再次向C借錢,C借給A,請求成功。
第二種:用request。B沒有錢,但是B向C借錢然後給A,請求成功。這次A只發送了一次請求,他並不知道借的錢是C的。
用response方法是這樣的:
response.sendRedirect( );
用resquest方法:
request.setAttribute("key","value");
request.getRequestDispatcher("index.jsp").forward(request,response);
這裡的setAttribute傳遞的參數只能由request.getAttribute( )來接收。request.getAttribute( )方法傳回值是object型,在使用時要注意類型轉換。
寫一段範例程式碼:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <base href="<%=basePath%>"> 7 8 <title>登陸頁面</title> 9 </head>10 11 <body>12 <h2>登陸頁面</h2>13 <%14 String errorCode =(String)request.getAttribute("error");//request.getParameter("error");15 if(errorCode != null && ! "".equals("error") && "01".equals(errorCode)){16 %>17 <h3 style="color:red">使用者名稱或密碼錯誤!</h3>18 <%19 }20 %>21 22 <form action="login.jsp" method="post">23 <p>使用者名稱:<input type="text" name = "userName" /><br/></p>24 <p>密 碼:<input type="password" name ="userPwd" /><br/></p>25 <p><input type = "submit" value = "登陸" /><br/></p>26 </form>27 <a href="reg.jsp">註冊新使用者</a>28 29 </body>30 </html>
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 5 <html> 6 <head> 7 8 <title>登陸頁面</title> 9 10 </head>11 12 <body>13 <%14 String name = request.getParameter("userName");15 String pwd = request.getParameter("userPwd");16 if("shamuu".equals(name) && "123".equals(pwd)){17 %>18 <h3 style="color:red;">歡迎你!<%=name %></h3>19 <%20 }else{21 //response.sendRedirect("index.jsp?error=01");22 request.setAttribute("error","01");23 request.getRequestDispatcher("index.jsp").forward(request,response);24 25 }26 %>27 </body>28 </html>
jsp中 response和request區別