问题
当我们在写项目中运到404、500等错误时,页面上会显示如下错误信息:
那么问题来了,我们可不可以自己定制404错误页面呢
答案当然是Of Course的啦
步骤如下
(1)首先添加 WebMvcConfig 配置类
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
container.addErrorPages(error401Page,error404Page,error500Page);
}
};
}
}
(2)然后将我们制作的404.html、500.html放在static目录下就OK了。
此时我们再启动项目,随便输入一个访问地址就会发现重定向到了我们的404.html
参考信息来源:https://stackoverflow.com/questions/23574869/404-error-redirect-in-spring-with-java-config