Spring自定义注解处理Controller参数(参数解析类)

1.新建注解类

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface  PersonValue {
    /**
     * Alias for {@link #name}.
     */
    @AliasFor("name")
    String value() default "";

    /**
     * The name of the request parameter to bind to.
     * @since 4.2
     */
    @AliasFor("value")
    String name() default "";

    /**
     * Whether the parameter is required.
     * <p>Defaults to {@code true}, leading to an exception being thrown
     * if the parameter is missing in the request. Switch this to
     * {@code false} if you prefer a {@code null} value if the parameter is
     * not present in the request.
     * <p>Alternatively, provide a {@link #defaultValue}, which implicitly
     * sets this flag to {@code false}.
     */
    boolean required() default true;

    /**
     * The default value to use as a fallback when the request parameter is
     * not provided or has an empty value.
     * <p>Supplying a default value implicitly sets {@link #required} to
     * {@code false}.
     */
    String defaultValue() default ValueConstants.DEFAULT_NONE;

}

2. 实现HandlerMethodArgumentResolver接口

public class PersonValueMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
          //判断参数是否具有目标注解
        return parameter.hasParameterAnnotation( PersonValue.class); }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        try {
            HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);

            if (servletRequest != null) {
                String token = WebUtils.getCookie(servletRequest,"token").getValue();
                  //从Cooke中解析出person对象
                return JWTUtil.getPerson(token);
            }
        } catch (Exception e) {
            return null;

        }

        return null;
    }

}

3.启用配置

 <mvc:annotation-driven >
        <mvc:argument-resolvers>
            <bean class="com.xxxx.xxx.xxxx.PersonValueMethodArgumentResolver"></bean>
        </mvc:argument-resolvers>

4.应用

  public @ResponseBody  Response doEditPass(@PersonValue  person,
      @RequestBody @Valid PwdEditCmd pwdEditCmd,
      HttpServletResponse response, HttpServletRequest request) {
     ...
    }
  

文章仅在黑客派和本网站刊登,其他为盗载。