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

背景web

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

@RequestMapping("/hello")

@ResponseBody

public Object test(TUserEntity entity) {

    // to do 
    return entity;
}

TUserEntityapp

public classTUserEntity {

private int id;

private String name;

// getter setter

}

Application 入口ide

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

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

在spring boot中实现拦截器功能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 {

    }
}

自定义参数解析器post

@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"}
哈哈 我就是库密code

相关文章
相关标签/搜索