sridhar
sridhar

Reputation: 303

How to send the send status code as response for 404 instead of 404.jsp as a html reponse in spring?

I created web application in spring and handled exception mappings for 404 and 500.If system doesn't find any resources for requested URL it redirects into custom 404.jsp instead of regular 404 page.Everything works fine till have decided to add a webservice in my app.I have included one more controller as a webservice there is no view for this controller and this needs to be invoke through curl command.

User may get into change the curl script.If they changed the URL it should show 404 status code.But it returns the custom 404.jsp as a html response instead of status code.Because dispatcher servlet will takes all urls with /*.

How I can solve this issue?

Please share your suggestions.

Upvotes: 1

Views: 834

Answers (1)

user957654
user957654

Reputation:

Spring 3.2 introduced the @ControllerAdvice, and as mentioned in the documentation:

It is typically used to define @ExceptionHandler

That means you can use the @ControllerAdvice to assist your @Controller like the following:

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.NOT_FOUND)  // 404
    @ExceptionHandler(Exception.class)
    public void handleNoTFound() {
        // Nothing to do
    }
}

For further details please refer to this tutorial and this answer.

Upvotes: 1

Related Questions