Request redirection and Request dispatch
Redirection
-The sendredirect () method provided by the httpservletrequest interface is used to generate a 302 response code and a location response header to notify the client to re-access the URL specified in the location response header. The complete definition syntax is as follows:
• Public void sendredirect (string location) throws ioexception;
-The location parameter specifies the redirected URL, which can use the absolute URL and relative URL. The servlet container automatically converts the relative URL to the absolute URL and then generates the location header field.
Request dispatch
-The servlet API defines a requestdispatcher interface, commonly known as the request dispatcher. It defines the following two methods:
• Public void forward (servletrequest request, servletresponse response)
• Throws servletexception, ioexception;
• Public void include (servletrequest request, servletresponse response)
• Throws servletexception, ioexception;
-There are two ways to obtain the requestdispatcher instance:
• Call the getrequestdispatcher (string URL) method provided by the servletcontext interface.
• Call the getrequestdispatcher (string URL) method provided by the servletrequest interface.
Comparison between redirection and Request dispatch
Comparison between the redirection implemented by the sendredirect () method of httpservletresponse and the request forwarding implemented by the requestdispatcher forward () method:
1. Request distribution can only forward requests to other components in the same web application. redirection can be directed not only to other resources in the current application, but also to resources of other sites.
2. After the redirection access process ends, the URL displayed in the address bar of the browser changes from the initial URL address to the destination URL of the redirection. After the request forwarding process ends, the address bar of the browser remains unchanged.
3. The initiators and callers assigned requests share the same request instance and response instance, which belong to the same "Request/response" process; the initiators and callers of the redirection use their respective request instances and response instances, which are independent "Request/response" processes.
Transmit object data using request domain attributes
The httpservletrequest interface provides several methods to operate the objects stored in the request instance:
(1) Public void setattribute (string name, object OBJ): stores the object in the httpservletrequest instance.
(2) Public object getattribute (string name): searches for objects stored in the httpservletrequest instance.
(3) Public enumeration getattributenames (): returns an enumeration object that contains all attribute names in the httpservletrequest instance.
(4) Public void removeattribute (string name): deletes the attribute of the specified name from the httpservletrequest instance.