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>

You can map the error codes in web.xml like the following

    <error-page>
        <error-code>400</error-code>
        <location>/400</location>
    </error-page>

    <error-page>
        <error-code>404</error-code>
        <location>/404</location>
    </error-page>

    <error-page>
        <error-code>500</error-code>
        <location>/500</location>
    </error-page>

Now you can create a controller to map the url's that are hit when any of these error is found.

@Controller
public class HTTPErrorHandler{

    String path = "/error";

    @RequestMapping(value="/404")
    public String error404(){
       // DO stuff here 
        return path+"/404";
    }
    }

For full example see my tutorial about this