为spring get请求添加自定义的参数处理操作(如下划线转驼峰)
1.生成自己的注解(为了确定在哪些位置使用)
/** *关闭patchdelete的model处理,否则会报错 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public@interfaceAliasProcessor{ }
/** *处理Get请求参数的驼峰问题 *@authorlw */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public@interfaceValueFrom{ /** *参数名(别名)列表 */ String[]value(); }
2.实现自己的ServletModelAttributeMethodProcessor
/** *为了减少使用@RequestPath将get参数封装到实体类中重写ModelAttributeMethodProcessor *注:由于get请求为非raw请求,spring默认使用@ModelArrtribute注解,不会自动将下划线的数据转为驼峰数据 *所以需要自定义一个处理器,进行该操作* *@authorlw */ publicclassAliasModelAttributeMethodProcessorextendsServletModelAttributeMethodProcessor{ privateApplicationContextapplicationContext; /** *过滤掉patch请求,防止报错 */ @Override publicbooleansupportsParameter(MethodParameterparameter){ returnparameter.getMethodAnnotation(AliasProcessor.class)!=null; } publicAliasModelAttributeMethodProcessor(ApplicationContextapplicationContext){ super(true); this.applicationContext=applicationContext; } @Override protectedvoidbindRequestParameters(WebDataBinderbinder,NativeWebRequestrequest){ AliasDataBinderaliasBinder=newAliasDataBinder(binder.getTarget(),binder.getObjectName()); RequestMappingHandlerAdapterrequestMappingHandlerAdapter=this.applicationContext.getBean(RequestMappingHandlerAdapter.class); requestMappingHandlerAdapter.getWebBindingInitializer().initBinder(aliasBinder); aliasBinder.bind(request.getNativeRequest(ServletRequest.class)); } }
3.自己的数据处理类
/** *重新数据处理类 *@authorlw */ publicclassAliasDataBinderextendsExtendedServletRequestDataBinder{ publicAliasDataBinder(Objecttarget,StringobjectName){ super(target,objectName); } /** *复写addBindValues方法 *@parammpvs这里面存的就是请求参数的key-value对 *@paramrequest请求本身,这里没有用到 */ @Override protectedvoidaddBindValues(MutablePropertyValuesmpvs,ServletRequestrequest){ super.addBindValues(mpvs,request); //处理要绑定参数的对象 Class>targetClass=getTarget().getClass(); //获取对象的所有字段(拿到Test类的字段) Field[]fields=targetClass.getDeclaredFields(); //处理所有字段 for(Fieldfield:fields){ //原始字段上的注解 ValueFromvalueFromAnnotation=field.getAnnotation(ValueFrom.class); //若参数中包含原始字段或者字段没有别名注解,则跳过该字段 if(mpvs.contains(field.getName())||valueFromAnnotation==null){ continue; } //参数中没有原始字段且字段上有别名注解,则依次取别名列表中的别名,在参数中最先找到的别名的值赋值给原始字段 for(Stringalias:valueFromAnnotation.value()){ //若参数中包含该别名,则把别名的值赋值给原始字段 if(mpvs.contains(alias)){ //给原始字段赋值 mpvs.add(field.getName(),mpvs.getPropertyValue(alias).getValue()); //跳出循环防止取其它别名 break; } } } } }
4.注册到spring中
/** *为了获得context需要实现ApplicationContextAware接口 *@authorlw */ @Configuration publicclassWebmvcConfigimplementsApplicationContextAware{ @Autowired privateRequestMappingHandlerAdapteradapter; privateApplicationContextapplicationContext=null; @Override publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{ this.applicationContext=applicationContext; } /** *将自定义的processor添加到adapter中 */ @PostConstruct protectedvoidinjectSelfMethodArgumentResolver(){ ListargumentResolvers=newArrayList<>(); argumentResolvers.add(newAliasModelAttributeMethodProcessor(this.applicationContext)); argumentResolvers.addAll(adapter.getArgumentResolvers()); adapter.setArgumentResolvers(argumentResolvers); } }
补充知识:springboot-mybatis-下划线与驼峰自动转换mapUnderscoreToCamelCase
以前都是在mybatis.xml中来配置,但是springboot不想再用xml配置文件。网上搜寻了好久,才找到设置办法:
sessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
db配置文件源码:
packagecom.vip.qa.vop.config; importcom.alibaba.druid.pool.DruidDataSource; importorg.apache.ibatis.session.SqlSessionFactory; importorg.mybatis.spring.SqlSessionFactoryBean; importorg.mybatis.spring.annotation.MapperScan; importorg.springframework.beans.factory.annotation.Qualifier; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.annotation.Primary; importorg.springframework.core.io.support.PathMatchingResourcePatternResolver; importorg.springframework.jdbc.datasource.DataSourceTransactionManager; importjavax.sql.DataSource; importjava.util.Properties; /** *Createdbydanny.yaoon2017/10/25. */ @Configuration @MapperScan(basePackages=VOPDataSourceConfig.PACKAGE,sqlSessionFactoryRef="vopSqlSessionFactory") publicclassVOPDataSourceConfig{ staticfinalStringPACKAGE="com.vip.qa.vop.mapper.vop"; @Value("${vop.datasource.url}") privateStringdbUrl; @Value("${vop.datasource.username}") privateStringdbUser; @Value("${vop.datasource.password}") privateStringdbPassword; @Value("${vop.datasource.driver-class-name}") privateStringdbDriver; @Bean(name="vopDataSource") @Qualifier @Primary publicDataSourcevopDataSource(){ DruidDataSourcedataSource=newDruidDataSource(); dataSource.setDriverClassName(dbDriver); dataSource.setUrl(dbUrl); dataSource.setUsername(dbUser); dataSource.setPassword(dbPassword); returndataSource; } @Bean(name="vopSqlSessionFactory") @Qualifier @Primary publicSqlSessionFactoryvopSqlSessionFactory(@Qualifier("vopDataSource")DataSourcescepDataSource)throwsException{ finalSqlSessionFactoryBeansessionFactoryBean=newSqlSessionFactoryBean(); sessionFactoryBean.setDataSource(scepDataSource); PathMatchingResourcePatternResolverresolver=newPathMatchingResourcePatternResolver(); sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/vop/*.xml")); sessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); returnsessionFactoryBean.getObject(); } //@Bean(name="vopTransactionManager") //@Qualifier //publicDataSourceTransactionManagertestDataTransactionManager(){ //returnnewDataSourceTransactionManager(vopDataSource()); //} }
以上这篇为springget请求添加自定义的参数处理操作(如下划线转驼峰)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。