spring-boot 自定义解析器实现参数绑定

背景

在使用spring-boot进行的web开发中,会碰到需要为Controller实现自定义的参数装配,比如说我们在Controller层中定义的方法:其中的TUserEntity往往是我们从Request中根据token解析的,那本文介绍的就是如何实现参数正确匹配。


@RequestMapping("/hello")

@ResponseBody

public Object test(TUserEntity entity) {

    // to do 
    return entity;
}

TUserEntity


public classTUserEntity {

private int id;

private String name;

// getter setter

}

Application 入口

@SpringBootApplication
@ComponentScan(basePackageClasses = Application.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

在spring boot中实现拦截器功能

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //实际情况可能是从request中获得token,继而查找获得用户实体
        TUserEntity entity = new TUserEntity();
        entity.setId(30);
        entity.setName("curry");
        httpServletRequest.setAttribute("tUserEntity", entity);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

自定义参数解析器

@Component
public class MyArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(TUserEntity.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        return nativeWebRequest.getAttribute("tUserEntity", 0);
    }
}

以上基本就实现了功能,之后访问http://localhost:8080/hello可以得到response:
{"id":30,"name":"curry"}
哈哈 我就是库密

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值