Java 中的 request 和response 区别

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型,在使用时要注意类型转换。

 

写一段示例代码:

Jsp代码  收藏代码
  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>密&nbsp;&nbsp;码:<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>  

 

Jsp代码  收藏代码
  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> 
posted @ 2016-03-29 20:10  Mr张Kk  阅读(7623)  评论(0编辑  收藏  举报