How to redirect to an error page when invalid or unknown URL is requested in Spring Boot display

How to display custom error pages(JSP) when invalid or unknown URL is requested in spring boot. Can any one help me either in spring boot or spring MVC(java configuration). Example: error page should be displayed if I request /homee instead of /home.

Upvotes: 1

Views: 1304

Answers (2)

The Solution is

@Controller
public class CustomErrorPage implements ErrorController{
    @RequestMapping("/customError")
    public String handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (status != null) {
            Integer statusCode = Integer.valueOf(status.toString());

            if(statusCode == HttpStatus.NOT_FOUND.value()) {
                return "error";
            }
            else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return "error";
            }
        }
        return "error";
    }
    @Override
    public String getErrorPath() {
        return null;
    }
}

specify server.error.path=/customError in application.properties.Alternative to application.properties is

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class CustomErrorPageRegistrar {
    @Bean
    public ErrorPageRegistrar errorPageRegistrar() {
        return new ErrorPageRegistrar() {
            public void registerErrorPages(ErrorPageRegistry registry) {
                System.out.println("custom error page registered");
                registry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/customError"));
            }
        };
    }
}

Upvotes: 0

k-wasilewski
k-wasilewski

Reputation: 4653

You have to implement a controller like so:

@Controller
public class CustomErrorController extends BasicErrorController {

    public CustomErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status.equals(HttpStatus.INTERNAL_SERVER_ERROR)){
            return ResponseEntity.status(status).body(ResponseBean.SERVER_ERROR);
        }else if (status.equals(HttpStatus.BAD_REQUEST)){
            return ResponseEntity.status(status).body(ResponseBean.BAD_REQUEST);
        }
        return super.error(request);
    }
}

Upvotes: 3

Related Questions