在模型对象中设置一个 属性,它将被 spring mvc 的所有控制器方法共享
Setting a property in model object which will be shared by all controller method of spring mvc
我想在 Spring MVC 的应用程序范围内设置一些具有值的属性。而且我应该能够在视图层中访问它(我正在使用 freemarker)。该值应该在应用程序启动期间只加载一次。在 Spring MVC 应用程序中执行此操作的最佳做法是什么?
提前致谢。
您可以使用 @PostConstruct 在您的控制器上简单地注释一个 public void 方法。 This method is executed after dependencies have been injected
,在创建控制器实例后调用它。
您可以添加一个 PagePopulationInterceptor
来为所有页面添加值:
public class PagePopulationInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
modelAndView.addObject("exampleGlobalString", "stringValue");
modelAndView.addObject("exampleGlobalInt", 2);
DateTime exampleDate = new DateTime(2005, 3, 26, 12, 0, 0, 0);
modelAndView.addObject("exampleGlobalDateTime", exampleDate);
modelAndView.addObject("exampleGlobalDate", exampleDate.toDate());
modelAndView.addObject("japaneseMonth", exampleDate.monthOfYear().getAsText(Locale.JAPAN));
}
}
}
我想在 Spring MVC 的应用程序范围内设置一些具有值的属性。而且我应该能够在视图层中访问它(我正在使用 freemarker)。该值应该在应用程序启动期间只加载一次。在 Spring MVC 应用程序中执行此操作的最佳做法是什么?
提前致谢。
您可以使用 @PostConstruct 在您的控制器上简单地注释一个 public void 方法。 This method is executed after dependencies have been injected
,在创建控制器实例后调用它。
您可以添加一个 PagePopulationInterceptor
来为所有页面添加值:
public class PagePopulationInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
modelAndView.addObject("exampleGlobalString", "stringValue");
modelAndView.addObject("exampleGlobalInt", 2);
DateTime exampleDate = new DateTime(2005, 3, 26, 12, 0, 0, 0);
modelAndView.addObject("exampleGlobalDateTime", exampleDate);
modelAndView.addObject("exampleGlobalDate", exampleDate.toDate());
modelAndView.addObject("japaneseMonth", exampleDate.monthOfYear().getAsText(Locale.JAPAN));
}
}
}