传递的数字'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
答案 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,因此您必须将参数转换回其本机类型。如果您只是将其显示为消息,则可能不需要进行此转换。