Wou*_*ens 9 java spring exception-handling spring-mvc
有没有办法让我的@ExceptionHandler方法可以访问由@RequestMapping触发相关异常的方法填充的模型属性?
或者,更具体地说是我的问题:传递给我的视图的模型有一些填充的数据@ModelAttribute(例如用户帐户的详细信息)方法,我希望这些也可以在我的@ExceptionHandler方法中设置.
例如,由于我的错误视图页面使用与其他页面相同的标题和菜单,我想显示当前用户名(以及其他信息,例如未读消息的数量等).
我知道@ExceptionHandler存在于@Transaction(因为它应该!)之外,所以我显然不能只(并且不想)再次运行一些查询.相反,我想预先填充ModelMapor ModelAndView或者其他任何东西,并确保异常处理程序得到它 - 或者至少在渲染视图时使模型数据可用.
我希望这个问题有道理,我是Spring MVC的新手,所以我可能会在这里和那里混合一些概念......
该的Javadoc的ExceptionHandler状态对于可传递到处理程序方法的参数如下:
使用此注释注释的处理程序方法允许具有非常灵活的签名。它们可能有以下类型的参数,按任意顺序:
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.
Run Code Online (Sandbox Code Playgroud)
因此,为了填充您将用于显示错误的视图模型,您可能必须使用 WebRequest
认为这是可能的,但是:
http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
重要提示:模型不能是任何 @ExceptionHandler 方法的参数。相反,使用 ModelAndView 在方法内设置模型,如上面的 handleError() 所示。
似乎您必须像在任何其他控制器中一样传递 ModelAndView ,因此必须再次构建它+从 HttpServletRequest 中获取可能的值。
| 归档时间: |
|
| 查看次数: |
4824 次 |
| 最近记录: |