在利用spring的mvc开发过程中,需要将User对象从session中取出来使用。参照网上的做法,我利用了AnnotationMethodHandlerAdapter来解决这个问题。下面是XML代码,放到web-inf下面的springMVC配置文件中:
<bean id="userArgumentResolver" class="com.greatwall.module.yhqxgl.interceptor.UserArgumentResolver" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="customArgumentResolver">
<ref bean="userArgumentResolver"/>
</property>
</bean>
下面是java代码:
package com.greatwall.module.yhqxgl.interceptor;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import com.greatwall.module.yhqxgl.YhqxglConstants;
import com.greatwall.module.yhqxgl.domain.User;
public class UserArgumentResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
if (methodParameter.getParameterType().equals(User.class)) {
return webRequest.getAttribute(YhqxglConstants.GREATWALL_SESSION_USER, RequestAttributes.SCOPE_SESSION);
}
return UNRESOLVED;
}
}
调用的过程很简单,直接在controller对应的函数里面加入参数User即可。
@RequestMapping("/txn960204.do")
public void txn960204(HttpServletResponse response, HttpServletRequest req,SysCodedata sysCodedata,User user) {
try {
sysCodedata.setUpdateTime(DateUtils.currentDateTime());
sysCodedata.setUpdateUsername(user.getUsername());
sysCodedataService.updateOneSysCodedata(sysCodedata);
JsonUtils.success("修改保存代码明细表成功!", response);
} catch (ServiceException e) {
e.printStackTrace();
JsonUtils.error(e, response);
}
}