1, response
belongs to the redirect request;
The URL of its address bar will change;
Two requests are sent to the server;
2. Request
belongs to request forwarding;
The URL of its address bar does not change;
Send a request to the server;
Give a simple example of distinguishing them:
A to B to borrow money:
The first type: with response. b no money, the request failed, but B told A,c Rich. So a again to C borrow money, C lent a, request success.
The second type: use Request. B had no money, but B borrowed money from C and then gave a, and the request succeeded. This time a only sent a request, he did not know that the borrowed money is C.
This is done using the response method:
Response.sendredirect ();
Using the Resquest method:
Request.setattribute ("Key", "value");
Request.getrequestdispatcher ("index.jsp"). Forward (Request,response);
The parameters passed by SetAttribute here can only be received by Request.getattribute (). The return value of the Request.getattribute () method is an object type, and you should pay attention to the type conversion when used.
Write a sample code:
JSP code
- <%@ page language="java" import="java.util.*" pageencoding= "UTF-8"%>
- <! DOCTYPE HTML public "-//W3C//DTD HTML 4.01 transitional//en" >
- <base href="<%=basePath%>" >
- <title> Landing Page </title>
- <body>
- <%
- String errorCode = (string) request.getattribute ("error");//request.getparameter ("error");
- if (ErrorCode! = NULL &&!) Equals ("error") && "ErrorCode" (equals) {
- %>
"color:red" > Username or password Error!
- <%
- }
- %>
- <form action="login.jsp" method="POST" >
- <p> Username: <input type="text" name = "UserName"/><br/></p>
- <p> Secret Code: <input type="password" name ="Userpwd"/><br/></p>
- <p><input type = "Submit" value = "Login"/><br/></p>
- </form>
- <a href="reg.jsp" > Register new users </a>
- </body>
JSP code
- <%@ page language="java" import="java.util.*" pageencoding= "UTF-8"%>
- <! DOCTYPE HTML public "-//W3C//DTD HTML 4.01 transitional//en" >
- <title> Landing Page </title>
- <body>
- <%
- String name = Request.getparameter ("UserName");
- String pwd = Request.getparameter ("userpwd");
- if ("Shamuu". Equals (name) && "123". Equals (pwd)) {
- %>
"color:red;" > Welcome you! <%=name%>
- <%
- }else{
- Response.sendredirect ("index.jsp?error=01");
- Request.setattribute ("error","01");
- Request.getrequestdispatcher ("index.jsp"). Forward (Request,response);
- }
- %>
- </body>
Request and response differences in Java