We can get the RequestDispatcher object with the ServletContext simpley by calling getRequestDispatcher(String url) with the ServletContext object which finally returns the RequestDispatcher object. We have two possible options to dispatch the control after getting the object of RequestDispatcher by using include(req,res) and forward(req,res). 

We must mention the resource to which control has to be dispatched as a String parameter in getRequestDispather(String url) method  but should be start with " / " otherwise container throws IllegalArgumentException.

Why should be start the resource name with " / " ?
It is because we are getting RequestDispactcher object with ServletContext and which follows the context path. For any Servlet Application its context path is always web apps. So for the requested resource container always takes the path relative to the context. So its mandatory to mention " / " before writing url otherwise container will throw IllegalArgumentException.



If we are not writing " / " then container always search for the requested resource under the context path ( i.e web Apps ) which can never be possible because our all the resources are available under the web content folder.

A diagrammatic representation showing what is a context path


From the above directory structure let consider,
Current Resource - home.jsp
Requested Resource - login.jsp

Container always consider the relative path for the requested resource as context path in case of getting RequestDispatcher object with ServletContext that means dispatch must be with the context path. 
So here the context path is " /Application 1 ".

By writing " / " container understands that the requested resource is not in the current directory i.e here Application 1 , then search in the relevant directory either Web-content or src folder if request resource is a html/jsp or servlet respectively. 

To know about RequestDispatcher with Request object. 

1 comment:

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic