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?name=1234可以得到response:

{"id":30,"name":"curry"}

哈哈 我就是库密

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,951评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,766评论 18 399
  • 一套完整的登陆注册业务逻辑 准备部分基础工具类Basepackage com.jericho.tools;impo...
    JerichoPH阅读 2,480评论 0 9
  • 小编费力收集:给你想要的面试集合 1.C++或Java中的异常处理机制的简单原理和应用。 当JAVA程序违反了JA...
    八爷君阅读 4,671评论 1 114
  • 本文的目的是简单介绍Spring Boot的一些入门配置的Quick Start,帮助快速上手; 不涉及Sprin...
    晓峰的简书阅读 2,461评论 2 3