springMVC自定义方法属性解析器

使用场景例子:

用户登陆系统一般会往Session里放置一个VO对象,然后在controller里会来获取用户的userId等信息。

之前的写法是:@SessionAttributes配合@ModelAttribute来进行参数值的注入,但这样需要写2个注解,其中SessionAttributes加在类上,ModelAttribute加在方法的属性上。

SpringMVC提供了HandlerMethodArgumentResolver接口来处理我们的自定义参数的解析。

例子:

1、获取用户信息的注解类

import java.lang.annotation.*;

/**
* <p>绑定当前登录的用户</p>
* <p>不同于@ModelAttribute</p>
*/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CurrentUser { /**
* 当前用户在request中的名字
*
* @return
*/
String value() default "loginUser"; }

2、自定义的参数解析器

import com.gongren.cxht.pay.web.shiro.bind.annotation.CurrentUser;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer; /**
* <p>自定义方法参数解析器
*/
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver { public CurrentUserMethodArgumentResolver() {
} @Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(CurrentUser.class)) {
return true;
}
return false;
} @Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);
//从session的scope里取CurrentUser注解里的value属性值的key的value
return webRequest.getAttribute(currentUserAnnotation.value(), NativeWebRequest.SCOPE_SESSION);
}
}

3、将自定义的解析器加入springmvc的配置文件里

<mvc:annotation-driven>
<mvc:argument-resolvers>
<!-- SESSION USER -->
<bean class="com.test.CurrentUserMethodArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>

在controller里的使用方法:

@RequestMapping(value = "/test")
public String test(@CurrentUser AccUserVo user) { }
上一篇:cocos2d-x 3.0游戏实例学习笔记《卡牌塔防》第七步---英雄要升级&属性--解析csv配置文件


下一篇:python – 如果安装的模块在zip文件的顶层添加.py文件,则Airflow打包的DAG将无法工作