Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a 404 controller using Spring Boot?

I'd like to return a custom 404 error using SpringBoot, but I'd like to be able to add some server-side logic to it, not just serve a static page.

1. I switched off the default whitelabel page in application.properties

error.whitelabel.enabled=false

2. I added a Thymeleaf error.html under resources/templates

This works by the way. The page is served, but no controller is called.

3. I created a class Error to be the "Controller"

package com.noxgroup.nitro.pages;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/error")
public class Error {

    @ExceptionHandler
    public String index() {
        System.out.println("Returning Error");
        return "index";
    }

}

Unfortunately, I'm not seeing Returning Error printed anywhere in the console.

I'm using the Embedded Tomcat with Spring Boot. I've seen various options, non of which seem to work including using @ControllerAdvice, removing the RequestMapping, etc. Neither work for me.

like image 271
sparkyspider Avatar asked Mar 06 '15 11:03

sparkyspider


People also ask

How do I create a 404 page in spring boot?

We first need to create a custom HTML error page. If we save this file in resources/templates directory, it'll automatically be picked up by the default Spring Boot's BasicErrorController. We can be more specific by naming the file with the HTTP status code we want it used e.g. saving the file as 404.

What is 404 error in spring boot?

As with any web application or website, Spring MVC returns the HTTP 404 response code when the requested resource can't be found.


2 Answers

The servlet container is going to pick up the 404 before it can get to Spring, so you'll need to define an error page at servlet container level, which forwards to your custom controller.

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

  @Override
  public void customize(ConfigurableEmbeddedServletContainer container) {
    container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error"));
  }

}
like image 67
ikumen Avatar answered Sep 22 '22 15:09

ikumen


Easiest way I found was to implement the ErrorController.

@Controller
public class RedirectUnknownUrls implements ErrorController {

    @GetMapping("/error")
    public void redirectNonExistentUrlsToHome(HttpServletResponse response) throws IOException {
        response.sendRedirect("/");
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
like image 27
hennr Avatar answered Sep 21 '22 15:09

hennr