SpringMVC异常处理:如何显示错误页面中传递的参数?

时间:2016-02-25 20:44:20

标签: spring-mvc tomcat exception-handling

传递的数字'12'不存在。我想在error.jsp页面中显示。 “名为'12'的产品不存在。我可以用什么方法来显示这些信息?

SpringMVC代码

@ExceptionHandler(Exception.class)
public ModelAndView errorHandler(HttpServletRequest req, Exception exception) {
    logger.error("Request: " + req.getRequestURL() + " raised " + exception);

    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", exception);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("product/error");
    return mav;
  }

Tomcat控制台

15:38:23.911 [http-bio-8080-exec-11] ERROR c.p.s.c.controller.ProductController - Request: http://localhost:8080/springchocolatestore/products/12 raised java.lang.RuntimeException

1 个答案:

答案 0 :(得分:0)

如果您尝试访问的参数是查询字符串参数,则可以从HttpServletRequest对象轻松访问它:

// Assuming that your parameter is named "num".
@ExceptionHandler(Exception.class)
public ModelAndView errorHandler(HttpServletRequest req, Exception exception) {
    logger.error("Request: " + req.getRequestURL() + " raised " + exception);
    ModelAndView mav = new ModelAndView();
    if (req.getParameterMap().containsKey("num")){
        mav.addObject("num", Integer.parseInt(req.getParameter("num"));
    } 
    mav.addObject("exception", exception);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("product/error");
    return mav;
  }

所有查询字符串参数都被格式化为String个对象,因为它们必须序列化为URL,因此您必须将参数转换回其本机类型。如果您只是将其显示为消息,则可能不需要进行此转换。