Servlet forwarding steps: first bind the data to the request object; then obtain the forwarder; finally, in the forwarded destination component, obtain the binding value based on the binding name, if the corresponding value does not exist , just return null.
Forwarding is when a web component (servlet/jsp) passes the unfinished processing to another web component through the container for further completion.
Generally, after a servlet obtains the data, it forwards it to a jsp, and the jsp generates the corresponding page based on the data.
Recommended course: Java Tutorial.
How does Servlet forward?
step1. Bind the data to the request object.
request.setAttribute(String name,Object obj);
For example:
request.setAttribute("emplist",emplist);
step2. Obtain the forwarder
RequestDispatcher rd = request.getRequestDispatcher(String uri);
uri: It is the destination component to be forwarded
For example:
RequestDispatcher rd = request.getRequestDispatcher("empList3.jsp");
step3. Forwarding
rd.forward(request,response);
In the forwarded destination component, the binding value can be obtained based on the binding name. If the corresponding value is not exists, returns null.
Object request.getAttribute(String name);
Problems that need attention when forwarding
Out.close and out.flush cannot be called before forwarding.
Before forwarding, the container will clear the cached data on the response object.
Forwarding features
After forwarding, the address in the browser address bar remains unchanged.
The forwarding destination can only be the address of a component within the same application.
The above is the detailed content of How to forward Servlet. For more information, please follow other related articles on the PHP Chinese website!