Now we've got a basic idea of how request mapping works. I also mentioned that every web request first comes to the Dispatcher servlet, but the question is how does the Dispatcher servlet know it should handle every incoming request? The answer is we explicitly instructed it to do so through the getServletMappings
method of the DispatcherServletInitializer
class. Yes, when we return the string array containing only the "/
" character, it indicates the DispatcherServlet
configuration as the default servlet of the application. So every incoming request will be handled by DispatcherServlet
.
Let's observe what will happen when we change the return value of the getServletMappings
method.
DispatcherServletInitializer
and change the return value of the getServletMappings
method as return new String[] { "/app/*"}
; basically your getServletMappings
method should look like the following after your change:@Override protected String[] getServletMappings() { return new String[] { "/app/*"}; }
http://localhost:8080/webstore/welcome
. You will see the HTTP Status 404 error page in the browser.http://localhost:8080/webstore/app/welcome
and you will be able to see the same welcome message in the browser.getServletMappings
method to its original value. Basically, your getServletMappings
method should look as follows after your change: @Override
protected String[] getServletMappings() {
return new String[] { "/"};
}
As I have already mentioned, we can consider the DispatcherServletInitializer
class as equivalent to web.xml
as it extends from the AbstractAnnotationConfigDispatcherServletInitializer
. If you look close enough, we are overriding three important methods in DispatcherServletInitializer
, namely:
getRootConfigClasses
: This specifies the configuration classes for the root application contextgetServletConfigClasses
: This specifies the configuration classes for the Dispatcher servlet application contextgetServletMappings
: This specifies the servlet mappings for DispatcherServlet
Typically, the context loaded using the getRootConfigClasses
method is the root context, which belongs to the whole application, while the one initialized using the getServletConfigClasses
method is actually specific to that Dispatcher servlet. Technically, you can have multiple Dispatcher servlets in an application and so multiple such contexts, each specific for the respective Dispatcher servlet but with the same root context.
In step 1, when we changed the return value of the getServletMappings
method, we instructed DispatcherServlet
to handle only the web requests that start with a prefix text of /app/
. That's why we entered the URL
http://localhost:8080/webstore/welcome
. We saw the HTTP Status 404 error page in the browser, since the URL request path didn't start with the /app/
prefix. But when we tried the URL http://localhost:8080/webstore/app/welcome
, we were able to see the same welcome message in the browser as the URL started with the /app/
prefix.