【问题标题】:How to return jsp with custom ErrorController?如何使用自定义ErrorController返回jsp?
【发布时间】:2020-05-07 03:00:39
【问题描述】:

我正在尝试返回自定义错误页面。在this guide 之后,我创建了我的错误控制器,如下所示:

@Controller
public class ErrorResource implements ErrorController  {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public Response handleError(HttpServletRequest request) {
        System.out.println("error handler called");
        try {
            Map<String, Object> model = new HashMap<>();
            return Response.ok(new Viewable("/path/to/jsp", model)).build();
        } catch (Exception e) {
            System.out.println("Exception thrown: " + e);
            throw new RuntimeException();
        }
    }
}

现在,而不是像这样的白标错误页面:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed May 06 19:02:36 PDT 2020
There was an unexpected error (type=Internal Server Error, status=500).

我反而看到了这个:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

null
There was an unexpected error (type=null, status=null).

在我的普通文件中,我可以返回一个 jsp 就好了。例如,以下对我来说很好:

@Path("/")
public class Resource {

    @Context
    private HttpServletResponse response;

    @GET
    @Path("/swift/containers")
    @Consumes("application/x-www-form-urlencoded")
    @Produces({ "text/html" })
    public Response getContainersPage() {
        Map<String, Object> model = new HashMap<>();
        model.put("containers", getContainers());
        return Response.ok(new Viewable("/path/to/jsp", model)).build();
    }
}

我已经确认该方法被调用,因为“错误处理程序调用”被打印出来。不会打印任何异常消息。

我错过了什么?

【问题讨论】:

  • 另外,当我将可查看路径更改为一些随机的、不正确的路径时,不会打印任何错误消息,并且我会得到相同的带有空值的 Whitelabel 错误页面

标签: java spring-boot jsp


【解决方案1】:

我猜你没有禁用错误 whitelabel 属性或没有在 pom.xml 中添加 thymeleaf 依赖项 你更新了吗

你的 application.properties 像这样吗?

server.error.whitelabel.enabled=false

和 pom.xml 这样?

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

【讨论】:

  • 由于我已经拦截了 /error 调用,我认为不需要禁用白标签页面。当我禁用它时,我只会收到经典的 500 内部服务器错误(我认为是 Tomcat 的默认错误页面)。添加 Thymeleaf 依赖项,我可以让自定义 .html 页面正常工作,但这与我一直使用的 .jsp 页面完全不同,如果可能,我希望保持逻辑一致。
猜你喜欢
  • 2014-01-05
  • 2017-03-26
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 2023-03-27
  • 2012-05-22
相关资源
最近更新 更多