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型,在使用時要注意類型轉換。
寫一段示例代碼:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>登陸頁面</title>
- </head>
- <body>
- <h2>登陸頁面</h2>
- <%
- String errorCode =(String)request.getAttribute("error");//request.getParameter("error");
- if(errorCode != null && ! "".equals("error") && "01".equals(errorCode)){
- %>
- <h3 style="color:red">用戶名或密碼錯誤!</h3>
- <%
- }
- %>
- <form action="login.jsp" method="post">
- <p>用戶名:<input type="text" name = "userName" /><br/></p>
- <p>密 碼:<input type="password" name ="userPwd" /><br/></p>
- <p><input type = "submit" value = "登陸" /><br/></p>
- </form>
- <a href="reg.jsp">注冊新用戶</a>
- </body>
- </html>
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>登陸頁面</title>
- </head>
- <body>
- <%
- String name = request.getParameter("userName");
- String pwd = request.getParameter("userPwd");
- if("shamuu".equals(name) && "123".equals(pwd)){
- %>
- <h3 style="color:red;">歡迎你!<%=name %></h3>
- <%
- }else{
- //response.sendRedirect("index.jsp?error=01");
- request.setAttribute("error","01");
- request.getRequestDispatcher("index.jsp").forward(request,response);
- }
- %>
- </body>
- </html>

