Art*_*Art 15 spring spring-mvc
我有一个数据驱动(缓存)的菜单,它是一个全局组件.我希望能够为每个请求注入菜单项,因为每个页面都将使用它.什么是最好的地方?我正在使用基于注释的Spring3.我能想到的最佳解决方案是使用OncePerRequestFilter并在其中添加或对Controller进行子类化,但不确定如何使用@Controller注释.
ska*_*man 13
我可以想到两个简单的选择:
每个@Controller类将数据公开为注释的方法@ModelAttribute,例如
@ModelAttribute
public MyData getMyData() {
...
}
Run Code Online (Sandbox Code Playgroud)
但是,如果你有多个控制器,这并不是很好.此外,这具有令人讨厌的副作用,即为myData每个重定向编码URL
我建议改为实现a HandlerInterceptor,并将数据公开给每个请求.你不能使用任何注释-lovin,但它最好以这种方式与你的业务逻辑分开.这与你的OncePerRequestFilter想法类似,但更多的是Spring-y.
从Spring 3.2开始,您可以使用@ControllerAdvice而不是在每个Controller中使用@ ExceptionHandler,@ InitBinder和@ModelAttribute.它们将应用于所有@Controller bean.
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class GlobalBindingInitializer {
@InitBinder
public void registerCustomEditors(WebDataBinder binder, WebRequest request) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
}
Run Code Online (Sandbox Code Playgroud)
如果您已经开始使用Spring Roo生成的代码,或者使用include-filter限制component-scan扫描的注释,那么在webmvc-config.xml中添加所需的过滤器
<!-- The controllers are autodetected POJOs labeled with the @Controller annotation. -->
<context:component-scan base-package="com.sensei.encore.maininterface" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
<!-- ADD THE BELOW LINE -->
<context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/>
</context:component-scan>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8218 次 |
| 最近记录: |