我有一个spring boot web应用程序,我将其部署为tomcat中的war文件。我不希望用户显示白标错误页面。我已经取得了一些进展,但需要将其重新指向错误页面。
以下代码是/ error白标错误页面是自定义错误消息。但是我想将它重定向到我的Web应用程序资源中的模板文件夹下的error.jsp或error.html。我尝试将 @RestController 改为 @Controller 而没有运气。
import org.springframework.boot.autoconfigure.web.ErrorController;
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 "Unexpected error has happened.Please contact administrator!!!";
}
@Override
public String getErrorPath() {
System.out.println("-- Error Page GET --");
return "error";
}
}
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.0.1.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- Provided (for embedded war support) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4</version>
</dependency>
答案 0 :(得分:5)
关闭application.properties
server.error.whitelabel.enabled=false
答案 1 :(得分:2)
您可以在Spring中编写自己的异常处理程序并重定向到错误页面
下面是处理Exception
及其子类
@ExceptionHandler(Exception.class)
public ModelAndView globalExceptionHandler(Exception e) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("message", e.getMessage());
return modelAndView;
}
您可以在控制器中编写任意数量的异常处理程序,也可以缩小处理程序中需要的异常,返回相应的错误页面。
查看文档