背景
在使用spring-boot进行的web开发中,会碰到需要为Controller实现自定义的参数装配,比如说我们在Controller层中定义的方法:其中的TUserEntity往往是我们从Request中根据token解析的,那本文介绍的就是如何实现参数正确匹配。
@RequestMapping("/hello")@ResponseBodypublic 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中实现拦截器功能
@Componentpublic 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 { }}
自定义参数解析器
@Componentpublic 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); }}
以上基本就实现了功能,之后访问可以得到response:
{"id":30,"name":"curry"} 哈哈 我就是库密