gpt4 book ai didi

java - 使用 JSP 显示 Spring 处理的异常消息

转载 作者:行者123 更新时间:2023-11-30 06:16:15 24 4
gpt4 key购买 nike

我是 Spring 新手,也是 JSP 新手。我在项目中工作,我需要创建一个页面,在出现特定异常时应用程序将被重定向。我有抛出异常之一的服务方法。此方法在我们的页面 Controller 之一中调用,带有 @RequestMapping 注释。因此,为了重定向到特定的错误页面,我使用 @ExceptionHanlder 创建了两个方法来处理此 Controller 中的此异常。外观:

@ExceptionHandler(IllegalStateException.class)
public ModelAndView handleIllegalStateException (IllegalStateException ex) {
ModelAndView modelAndView = new ModelAndView("redirect:/error");
modelAndView.addObject("exceptionMsg", ex.getMessage());
return modelAndView;
}

但还不够。我还需要创建 ErrorPageController:

@Controller
@RequestMapping("/error")
public class ErrorPageController {
@RequestMapping(method = RequestMethod.GET)
public ModelAndView displayErrorPage() {
return new ModelAndView("error");
}
}

现在可以显示错误页面了。但我的问题是,我无法在 JSP 中显示错误消息...我有:

<h3>Error page: "${exceptionMsg}"</h3>

但我没有看到消息;/取而代之的是,我在 URL 中看到了消息:

localhost/error?exceptionMsg=Cannot+change+participation+status+if+the+event+is+cancelled+or+it+has+ended.

这是错误的,因为在 URL 中我只想有一个“localhost/error”,仅此而已。我想在 JSP 中显示此消息。

最佳答案

要解决这两个问题(显示消息,并拥有正确的 url),您应该在原始代码中将异常处理程序方法更改为例如

@ExceptionHandler(IllegalStateException.class)
public RedirectView handleIllegalStateException(IllegalStateException ex, HttpServletRequest request) {
RedirectView rw = new RedirectView("/error");
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
if (outputFlashMap != null) {
outputFlashMap.put("exceptionMsg", ex.getMessage());
}
return rw;
}

为什么?如果您希望您的属性通过重定向持续存在,您需要将它们添加到 flash 范围。上面的代码使用了文档中的 FlashMap

A FlashMap is saved before the redirect (typically in the session) and is made available after the redirect and removed immediately.

如果它是一个普通的 Controller 方法,你可以简单地添加 RedirectAttributes 作为参数,但是在 @ExceptionHandler 方法上,RedirectAttributes 的参数没有被解析,所以你需要添加 HttpServletRequest 并使用 RedirectView。

关于java - 使用 JSP 显示 Spring 处理的异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27601302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com