简体   繁体   English

如何在Spring Boot中创建自定义错误页面

[英]How to create custom error page in spring boot

I read the reference from the following url 我从以下网址阅读了参考

Customized 404 error page in spring-boot and its working. spring-boot中的自定义404错误页面及其工作。

In the above document they used .HTML pages. 在上述文档中,他们使用了.HTML页面。 But i need .jsp pages. 但是我需要.jsp页面。

src/
+- main/
   +- java/
   +- resources/
       +- public/
           +- error/
           |   +- 404.html

ie. 即。 404.html to 404.jsp 404.html至404.jsp

Is it possible? 可能吗?

Yes it is possible. 对的,这是可能的。

You just need to configure 您只需要配置

InternalViewResolver

as with .jsp extension. 与.jsp扩展名一样。

Edit: 编辑:

Please check the below sample code. 请检查以下示例代码。

private static final String VIEW_RESOLVER_PREFIX = "your/jsp/location";
private static final String VIEW_RESOLVER_SUFFIX = ".jsp";

@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
    viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX);
    return viewResolver;
}

You need first to configure spring boot to use jsp as it is not offered out-of-the-box. 您首先需要配置spring boot以使用jsp,因为它不是现成的。 In maven pom.xml, add the following dependencies: 在maven pom.xml中,添加以下依赖项:

    <!-- Need this to compile JSP -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jdt.core.compiler</groupId>
        <artifactId>ecj</artifactId>
        <version>4.6.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- JSTL for JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

In application.properties: 在application.properties中:

spring.mvc.view.prefix= /WEB-INF/jsp/
spring.mvc.view.suffix= .jsp

The way I have configured it, the .jsp files then need to be in src/main/webapp/WEB-INF/jsp folder so create it if needed. 按照我的配置方式,.jsp文件需要位于src / main / webapp / WEB-INF / jsp文件夹中,因此可以根据需要创建它。 Let's say I then create a file src/main/webapp/WEB-INF/jsp/error/404.jsp. 假设我然后创建了一个文件src / main / webapp / WEB-INF / jsp / error / 404.jsp。 To access it from my controller, I simply refer to it as 要从我的控制器访问它,我只是将其称为

return "error/404";

since spring boot will automatically add the view prefix and suffix for me. 因为spring boot会自动为我添加视图前缀和后缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM