Are you creating the project from scratch? Are you able to use Spring-Boot? Spring Boot provides a lot of nice error handling functionality out of the box that can be easily modified.
Either way, if you just want to use standard error page mapping in the web.xml, or example:
<error-page>
<error-code>404</error-code>
<location>/error/404</location>
</error-page>
When your application returns a 404 status code, the request will be intercepted and forwarded internally to the endpoint /error/404
- which can just be any endpoint in your spring app, so can do any dynamic stuff that you would in a normal controller.
To do it programatically, without Spring Boot, you could create a Filter class that wraps all requests and just catches exceptions and checks for non 2XX response codes and forwards/handles appropriately - this is basically the solution that the Spring Boot guys implemented (see the ErrorPageFilter class).
To access info about the exception, that can be accessed from the request - see here for similar answer: https://stackoverflow.com/a/1034667/258813