I am currently trying to create a Controller to handle all unknown URLs globally. So what I did was create a controller similar to the one below
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/**")
public class UnknownUrlController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getError404() {
return "/error404";
}
}
My intention was to ensure that the default servlet which just returns a String "Not Found" to the browser was not invoked. This strategy worked since all unknown URL was handled by this Controller.
However the issue was that the controller was also invoked for all my static resources (images, js and css files) I had configured in my WebMvcConfigurerAdapter as follows
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
}
so instead of my static files served to the browser, my error pages were served in its place. Although I later understood that controllers mappings take precedence over static resources from this answer . This is the reason I would like to know how to exclude my resources url mappings from being handled by this controller so it would only be concerned with trapping the unknown URLs.
Before proceeding with this strategy I had tried some other things that I could not get to work (I am probably missing something)
- Setting the throwExceptionIfNoHandlerFound field of my DispatcherServlet to true so that the exception that should be thrown when no handler for a URL mapping is found and then handle it with globally as described here . However it seems a default handler is always assigned for unknown paths (/**) and so no exception is ever thrown.
- created an application.properties files and set spring.mvc.throw-exception-if-no-handler-found=true.
All my configuration are Java based without any xml files and would prefer to keep it that way.