有没有办法让我的@ExceptionHandler
方法可以访问由触发相关例外的@RequestMapping
方法填充的模型属性?
或者,更具体地说是针对我的问题:传递给我的视图的模型有一些从@ModelAttribute
填充的数据(例如用户帐户的详细信息)方法,我希望这些数据也可以设置为我的@ExceptionHandler
方法。
例如,由于我的错误视图页面使用与其他页面相同的标题和菜单,因此我想显示当前用户名(以及其他信息,例如未读消息的数量等)。
我知道@ExceptionHandler
存在于@Transaction
之外(因为它应该!),所以我显然不能(并且不想)再次运行一些查询。相反,我想预先填充ModelMap
或ModelAndView
或其他任何东西,并确保异常处理程序得到它 - 或者至少在渲染视图时使模型数据可用
我希望这个问题有道理,我是Spring MVC的新手,所以我可能会在这里和那里混合一些概念......
答案 0 :(得分:4)
ExceptionHandler
的{{3}}声明了以下关于可以传递给处理程序方法的参数:
允许使用此注释注释的处理程序方法 拥有非常灵活的签名。他们可能有争论 以下类型,按任意顺序:
1. An exception argument: declared as a general Exception or as a more specific exception. This also serves as a mapping hint if the annotation itself does not narrow the exception types through its value().
2. Request and/or response objects (Servlet API or Portlet API). You may choose any specific request/response type, e.g. ServletRequest / HttpServletRequest or PortletRequest / ActionRequest / RenderRequest. Note that in the Portlet case, an explicitly declared action/render argument is also used for mapping specific request types onto a handler method (in case of no other information given that differentiates between action and render requests).
3. Session object (Servlet API or Portlet API): either HttpSession or PortletSession. An argument of this type will enforce the presence of a corresponding session. As a consequence, such an argument will never be null. Note that session access may not be thread-safe, in particular in a Servlet environment: Consider switching the "synchronizeOnSession" flag to "true" if multiple requests are allowed to access a session concurrently.
4. WebRequest or NativeWebRequest. Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.
5. Locale for the current request locale (determined by the most specific locale resolver available, i.e. the configured LocaleResolver in a Servlet environment and the portal locale in a Portlet environment).
6. InputStream / Reader for access to the request's content. This will be the raw InputStream/Reader as exposed by the Servlet/Portlet API.
7. OutputStream / Writer for generating the response's content. This will be the raw OutputStream/Writer as exposed by the Servlet/Portlet API.
8. Model as an alternative to returning a model map from the handler method. Note that the provided model is not pre-populated with regular model attributes and therefore always empty, as a convenience for preparing the model for an exception-specific view.
因此,为了填充您将用于显示错误的视图模型,您可能必须使用WebRequest
答案 1 :(得分:1)
认为可能,但是:
http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
重要说明:模型可能不是任何参数 @ExceptionHandler方法。而是在方法内部设置模型 使用ModelAndView,如上面的handleError()所示。
似乎你不能像在任何其他控制器中一样传递ModelAndView,因此必须再次构建+从HttpServletRequest中获取可能的值。