100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > springMVC自定义方法属性解析器

springMVC自定义方法属性解析器

时间:2022-09-01 14:29:10

相关推荐

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)@Documentedpublic @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() {}@Overridepublic boolean supportsParameter(MethodParameter parameter) {if (parameter.hasParameterAnnotation(CurrentUser.class)) {return true;}return false;}@Overridepublic Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);//从session的scope里取CurrentUser注解里的value属性值的key的valuereturn 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) {}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。