Sheriff Hussain
Sheriff Hussain

Reputation: 224

throwing NoHandlerFoundException and configuring custom 404 page in SpringBoot

I have been learning Spring for just 7 months. While I used spring MVC only, i want to configure custom 404 page by throwing NoHandlerFoundException or enabling it in the dispatcher servlet. Now, i am learning spring boot, can anyone explain to me?

Upvotes: 1

Views: 3354

Answers (1)

PraveenKumar Lalasangi
PraveenKumar Lalasangi

Reputation: 3543

I had the same issue, got it resolved. Below given steps to solve the same.

  1. Create a class GlobalExceptionHandler annotated with @ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler 
{
    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleNotFoundError(Exception ex) 
    {
        return "redirect:/yourCustom404page";
    }
}
  1. By default, when a page/resource does not exist the servlet container will render a default 404 page. If you want a custom 404 response then you need to tell DispatcherServlet to throw the exception if no handler is found. We can do this by setting the throwExceptionIfNoHandlerFound servlet initialization parameter to true

to achieve this

a. In spring-boot
spring.resources.add-mappings=false in your application.properties or yaml file.

b. If spring-mvc java based configuration is

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    ...

    @Override
    protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) 
    {
        final DispatcherServlet servlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
        servlet.setThrowExceptionIfNoHandlerFound(true);
        return servlet;
    }

}

c. if spring-mvc xml based configuration, initialize your dispatcher servlet like this

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

Upvotes: 1

Related Questions