【问题标题】:SpringMVC using @ExceptionHandler HTTP Status 500 - Expected session attributeSpringMVC 使用 @ExceptionHandler HTTP 状态 500 - 预期的会话属性
【发布时间】:2013-05-03 03:26:00
【问题描述】:

我想使用 @exceptionhandler 来捕获 HTTP 状态 500 - 预期的会话属性。我想在向用户显示错误的同一页面返回一条消息。

谁能指出我如何处理此异常并将消息返回到视图而不是重定向到另一个页面的示例。

这是我目前所拥有的,但是视图中的项目没有设置错误消息;

@ExceptionHandler(HttpSessionRequiredException.class)
    public RedirectView handleHttpSessionRequiredException(Exception ex, HttpServletRequest request) throws Exception
    {
        logger.info("In the handleHttpSessionRequiredException Handler Method");
        String referrer = request.getHeader("referer");
        RedirectView redirectView = new RedirectView(referrer);
        redirectView.addStaticAttribute("errorMessage","Execute A Query Then Retry");
        return redirectView;
    }

查看

<label id="errorMessage" name="errorMessage">${errorMessage}</label>

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

您可以获取引用并转发或重定向到它。例如

@ExceptionHandler(HttpSessionRequiredException.class)
public String (HttpServletRequest request) {
    String referrer = request.getHeader("referer");
    ...
    FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
flashMap.put("errorMessage","Execute A Query Then Retry");
    return "redirect:/my/url";
}

重定向 URL 是相对于应用程序路径的。您可以从referer中提取它。

【讨论】:

  • 我也在异常处理程序中尝试 redirectView.addStaticAttribute("errorMessage", ex.getMessage()) 但是它没有在视图中设置消息。该视图有一个标签
  • @dev_darin 关于如何设置重定向属性看here
  • 如果我更改方法类型以返回 RedirectView 以外的任何其他内容,则异常不会进入它。
  • @dev_darin 感谢您提出这个有趣的问题 ;) +1
【解决方案2】:

您可以通过执行以下操作从 @ExceptionHandler 方法返回 ModelAndView。

@ExceptionHandler(IOException.class)
public ModelAndView handleIOException(IOException ex) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("someObject", new SomeObject());
    modelAndView.setViewName("someView");
    return modelAndView;
}

问题在于找出您之前所在的当前页面。据我所知,没有办法从 ExceptionHandler 方法中获取当前模型和视图,因此您无法很好地了解要使用的视图。

我认为最好的办法是在控制器中捕获并处理异常。

【讨论】:

  • 这意味着我必须重定向到异常页面?
猜你喜欢
  • 2019-10-24
  • 1970-01-01
  • 2015-11-04
  • 2011-01-01
  • 2014-01-08
  • 2014-11-20
  • 2019-12-17
  • 1970-01-01
  • 2013-07-13
相关资源
最近更新 更多