Spring Boot配置404页面

在开发Web应用程序时,很重要的一点是设置合适的404页面,以便在用户访问不存在的资源时提供友好的提示。Spring Boot提供了方便的方式来配置自定义的404页面,让用户体验更加友好。

配置404页面

要配置自定义的404页面,我们可以使用Spring Boot提供的ErrorController接口。ErrorController是一个接口,用于处理错误请求并返回合适的错误页面。我们可以通过实现这个接口来自定义404页面。

首先,我们需要创建一个类,实现ErrorController接口,并在该类中处理404错误:

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomErrorController implements ErrorController {

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error() {
        return "404 - Page Not Found";
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

在上面的代码中,我们创建了一个名为CustomErrorController的类,实现了ErrorController接口,并且定义了error()方法来处理404错误。在error()方法中,我们返回了一个简单的错误信息。

配置404页面路径

接下来,我们需要在application.properties文件中配置404页面的路径:

server.error.path=/error

通过这个配置,我们告诉Spring Boot当遇到404错误时,去访问/error路径,并由CustomErrorController处理。

测试

为了测试我们的自定义404页面,我们可以在浏览器中访问一个不存在的页面,例如http://localhost:8080/nonexistent。如果一切配置正确,我们应该看到自定义的404页面显示“404 - Page Not Found”。

总结

通过以上步骤,我们成功配置了Spring Boot的自定义404页面。通过实现ErrorController接口,并配置404页面路径,我们可以方便地定制错误页面,提升用户体验。在开发Web应用程序时,设置合适的404页面是很重要的一点,希望本文的内容能帮助你更好地理解如何配置Spring Boot的404页面。