在利用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); } }