servlet's control distribution

A: distribution control is mainly done by the servlet RequestDispatcher object (since the entire web is present in the servlet container, it is not spring so as to specify a control distributor, which has been built inside the container in the web). Get RequestDispatcher There are two main ways, they are all under the definition of the interface ServletContext

1.public RequestDispatcher getRequestDispatcher(String path)

path is the absolute path of the resource, it should be a "/"

2.public RequestDispatcher getRequestDispatcher(String name)

name is registered in web.xml servlet corresponding name

Two: There are two ways to complete the request distribution

1.public void include(request,response);

The method may change so that other tasks generated resource static and dynamic content contained in its generated response

eg:ServletContext context = getServletContext();

  RequestDispatcher rd = context.getRequestDispatcher ( "HeaderServlet"); // HeaderServlet output stream comprising a header

  rd.include(res,rps);

  rps.getWriter.println("<FONT SIZE=*******");

  rd = context.getRequestDispatcher("/foot.html");

  rd.include(res.rps);

  This completes a common output flow to various components of the client

 

2.public void forward(request,response);

The method of making modified Servlet Servlet forwards the request to another Web or any other components, and other components or the Servlet will be responsible for further processing of the request and generates a response

eg:  RequestDispatcher rd = null;

    if(valid){

      rd = context.getRequestDispatcher("InboxServlet");

    }else{

      rd = context.getRequestDispatcher("error.jsp");

    }

    rd.forward(res,rps);

Let's look at the comparison of two methods:

forward method Methods include
When used to control web must be transferred to the other components

When using part of the processing must be performed by another component web. once

Processing is complete, the current web components to take back control

Before forwarding the request, forwarding the request web components should

Output streams for communicating with the client using

All shared web component of the output stream to communicate with the client

 

 

Reproduced in: https: //my.oschina.net/secyaher/blog/274429

Guess you like

Origin blog.csdn.net/weixin_33922670/article/details/91967076