Spring MVC: How to return custom 404 errorpages?
The solution is much simpler than thought. One can use one generic ResourceNotFoundException
defined as follows:
public class ResourceNotFoundException extends RuntimeException { }
then one can handle errors within every controller with an ExceptionHandler
annotation:
class MeterController {
// ...
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
return "meters/notfound";
}
// ...
@RequestMapping(value = "/{number}/edit", method = RequestMethod.GET)
public String viewEdit(@PathVariable("number") final Meter meter,
final Model model) {
if (meter == null) throw new ResourceNotFoundException();
model.addAttribute("meter", meter);
return "meters/edit";
}
}
Every controller can define its own ExceptionHandler
for the ResourceNotFoundException
.
modified your web.xml file.Using following code.
<display-name>App Name </display-name>
<error-page>
<error-code>500</error-code>
<location>/error500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>
Access this by following code.
response.sendError(508802,"Error Message");
Now add this code in web.xml.
<error-page>
<error-code>508802</error-code>
<location>/error500.jsp</location>
</error-page>