您的位置:首页 > 编程语言 > Java开发

springboot使用之四:错误页面404处理建议

2016-11-11 13:36 931 查看
每个项目可能都会遇到404,403,500等错误代码,如没有错误页面,则会给用户一个很不友好的界面,springboot项目同样也存在这个问题。

但在官方文档并没有相关配置信息,这就要求我们自己来实现了,查了下资料,并测试通过后,有一种方法比较简单可行。

对于springboot整合mvc这里就不赘述了,官方文档里有详细说明,这里针对错误页面404举个简单例子:

1.准备页面404.html,并将它放在templates目录下面

2.写一个配置类,并且实现接口EmbeddedServletContainerCustomizer ,如下:

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.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class ErrorPageConfig implements EmbeddedServletContainerCustomizer {

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


3.写一个controller,用于转发错误页面

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ErrorPageController  {

@RequestMapping("404")
public String toPage(){
return "404";
}

}


这时候,如果你有找不到的页面,就可以转发到你设定的404页面了。

对于500,403等其他错误码,同样的道理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: