@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Controller
public ModeAndView createUser(User user){
}
如何获取控制器方法createUser的参数 用户 值 在拦截者的帖子中?
答案 0 :(得分:0)
你不能直接。
正如您在参数中看到的那样,Interceptor
可以直接访问请求,响应和ModelAndView
。如果您需要访问方法参数user
,最简单的方法是将其放入模型中。
public ModeAndView createUser(User user){
ModelAndView mav = new ModelAndView();
mav.addAttribute("user", user);
...
return mav;
}
然后在拦截器postHandle
方法中,你只需要
User user = (User) modelAndView.getAttribute("user");
答案 1 :(得分:-1)
你可以写一个org.springframework.web.servlet.HandlerInterceptor。 (或其便利子类HandlerInterceptorAdapter)
@See:Spring Reference chapter: 15.4.1 Intercepting requests - the HandlerInterceptor interface
它有方法:
void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception;
在控制器完成之后和渲染视图之前调用此方法。所以你可以使用它来为ModelMap添加一些属性
示例:
public class VersionAddingHandlerInterceptor extends HandlerInterceptorAdapter {
/**
* The name under which the version is added to the model map.
*/
public static final String VERSION_MODEL_ATTRIBUTE_NAME =
"VersionAddingHandlerInterceptor_version";
/**
* it is my personal implmentation
* I wanted to demonstrate something usefull
*/
private VersionService versionService;
public VersionAddingHandlerInterceptor(final VersionService versionService) {
this.versionService = versionService;
}
@Override
public void postHandle(final HttpServletRequest request,
final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
modelAndView.getModelMap().
addAttribute(VERSION_MODEL_ATTRIBUTE_NAME,
versionService.getVersion());
}
}
}
<强> webmvc-config.xml中强>
<mvc:interceptors>
<bean class="demo.VersionAddingHandlerInterceptor" autowire="constructor" />
</mvc:interceptors>