RequestDispatcher from servletcontext on request

How are these two lines of code different and when should we use them?

1.

RequestDispatcher view = request.getRequestDispatcher("result.jsp");

      

2.

RequestDispatcher view = getServletContext().getRequestDispatcher("/result.jsp");

      

+3


source to share


1 answer


1) RequestDispatcher view = request.getRequestDispatcher("result.jsp");

Here

  • displayed relative to the current request. you need to pass the relative path jsp / html
  • to combine two servlets in the same web application.

java doc says,

The specified pathname can be relative, although it cannot propagate outside of the current servlet context. If the path starts with "/", it is interpreted as relative to the current context root. This method returns null if the servlet container cannot return a RequestDispatcher.

The difference between this method and ServletContext.getRequestDispatcher (java.lang.String) is this method can take a relative path.



2) RequestDispatcher view = getServletContext (). getRequestDispatcher ("/result.jsp");

Here

  • the view refers to the root of the servlet context, you must pass the absolute path jsp / html
  • to combine two web applications on the same / different servers.

java doc says,

The path must start with a "/" character and is interpreted as the current relative root of the context. Use getContext to get the RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.

+4


source







All Articles