执行重复的 Spring 控制器代码的最佳方式?
我有一个库方法 Common.addTheUsualStuffToTheModel(model)
,需要在我的应用程序中的每个控制器方法中向模型添加各种属性。
@RequestMapping(value = "/everypath", method = RequestMethod.GET)
public final String everyHandler(ModelMap model)
{
model = Common.addTheUsualStuffToTheModel(model);
return "everyPage";
}
到目前为止,我一直在每个处理程序方法中添加同一行:
model = Common.addTheUsualStuffToTheModel(model);
但恐怕这不符合“一次编写,到处使用”的原则。
如何避免在每个处理程序中重复此代码?
I have a library method Common.addTheUsualStuffToTheModel(model)
that needs to add various attributes to the model in every controller method in my app.
@RequestMapping(value = "/everypath", method = RequestMethod.GET)
public final String everyHandler(ModelMap model)
{
model = Common.addTheUsualStuffToTheModel(model);
return "everyPage";
}
So far I have been adding this same line to every handler method:
model = Common.addTheUsualStuffToTheModel(model);
But I'm afraid this is not consistent with the principle of "write once, use everywhere".
How do I avoid repeating this code in every handler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 拦截器和
来做到这一点在您的拦截器中,您可以添加任何内容作为请求属性(这实际上是模型属性所在的位置)。拦截器代码在每个方法(与拦截器映射匹配)之前或之后执行。
如果您不一定需要在控制器方法之前填充模型,则可以在
postHandle
方法中获取ModelAndView
对象。You can use an interceptor and
<mvc:interceptors>
to do thatIn your interceptor you can add anything as request attribute (which is in fact where the model attributes go). The interceptor code is executed before or after each method (that matches the interceptor mapping).
If you don't necessarily need the model to be populated before the controller method, in the
postHandle
method you get theModelAndView
object.指定 @ModelAttribute 注释的参考数据提供程序方法怎么样?如果您的所有控制器都有一个基类,并且该基类具有 @ModelAttribute 注释方法,那么我相信模型中的数据将可用于这些控制器处理的所有视图。查看 Spring 文档中的 15.3.2.8 。
What about specifying @ModelAttribute annotated reference data provider methods. If you had a base class for all of your controllers, and that base class had @ModelAttribute annotated methods then I believe that data would be available in the model for all views handled by those controllers. Have a look at 15.3.2.8 in the Spring docs.