这应该适合您的需要,使用HandlerInterceptor
自定义注释@Model
和反射。
模型.java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Model {
}
请求拦截器.java
@Service
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
try {
Class<?> clazz = request.getClass();
if (clazz.isAnnotationPresent(Controller.class)) {
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(Model.class)) {
field.set(request, new ModelMap());
break;
}
}
}
} catch (IllegalAccessException e) {
// log("Cannot access model field of controller " + clazz.getSimpleName());
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
try {
Class<?> clazz = request.getClass();
if (clazz.isAnnotationPresent(Controller.class)) {
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(Model.class)) {
ModelMap model = (ModelMap) field.get(request);
if (model != null) {
modelAndView.addAllObjects(model);
}
break;
}
}
}
} catch (IllegalAccessException e) {
// log("Cannot access model field of controller " + clazz.getSimpleName());
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
应用程序上下文.xml
<!-- register the interceptor -->
<mvc:interceptors>
<bean class="your.package.to.the.RequestInterceptor" />
</mvc:interceptors>
你的控制器.java
@Controller
public class YourController extends ConnectController {
@Model
private ModelMap model;
@Override
protected String connectView(){
// model is here available
model.addAttribute("attrName", "attrValue");
return "connect/status";
}
}