為spring get請求添加自定義的參數處理操作(如下劃線轉駝峰)
1.生成自己的注解(為了確定在哪些位置使用)
/** * 關閉patch delete的model處理,否則會報錯 */@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface AliasProcessor {}
/** * 處理Get 請求參數的駝峰問題 * @author lw */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface ValueFrom { /** * 參數名(別名)列表 */ String[] value();}
2.實現自己的ServletModelAttributeMethodProcessor
/** * 為了減少使用 @RequestPath 將get參數封裝到實體類中 重寫ModelAttributeMethodProcessor * 注:由于get請求為非raw請求,spring默認使用@ModelArrtribute注解,不會自動將下劃線的數據轉為駝峰數據 * 所以需要自定義一個處理器,進行該操作 * * @author lw */public class AliasModelAttributeMethodProcessor extends ServletModelAttributeMethodProcessor { private ApplicationContext applicationContext; /** * 過濾掉patch請求,防止報錯 */ @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getMethodAnnotation(AliasProcessor.class)!=null; } public AliasModelAttributeMethodProcessor(ApplicationContext applicationContext) { super(true); this.applicationContext=applicationContext; } @Override protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) { AliasDataBinder aliasBinder = new AliasDataBinder(binder.getTarget(), binder.getObjectName()); RequestMappingHandlerAdapter requestMappingHandlerAdapter = this.applicationContext.getBean(RequestMappingHandlerAdapter.class); requestMappingHandlerAdapter.getWebBindingInitializer().initBinder(aliasBinder); aliasBinder.bind(request.getNativeRequest(ServletRequest.class)); }}
3.自己的數據處理類
/** * 重新數據處理類 * @author lw */public class AliasDataBinder extends ExtendedServletRequestDataBinder { public AliasDataBinder(Object target, String objectName) { super(target, objectName); } /** * 復寫addBindValues方法 * @param mpvs 這里面存的就是請求參數的key-value對 * @param request 請求本身, 這里沒有用到 */ @Override protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) { super.addBindValues(mpvs, request); // 處理要綁定參數的對象 Class<?> targetClass = getTarget().getClass(); // 獲取對象的所有字段(拿到Test類的字段) Field[] fields = targetClass.getDeclaredFields(); // 處理所有字段 for (Field field : fields) { // 原始字段上的注解 ValueFrom valueFromAnnotation = field.getAnnotation(ValueFrom.class); // 若參數中包含原始字段或者字段沒有別名注解, 則跳過該字段 if (mpvs.contains(field.getName()) || valueFromAnnotation == null) { continue; } // 參數中沒有原始字段且字段上有別名注解, 則依次取別名列表中的別名, 在參數中最先找到的別名的值賦值給原始字段 for (String alias : valueFromAnnotation.value()) { // 若參數中包含該別名, 則把別名的值賦值給原始字段 if (mpvs.contains(alias)) { // 給原始字段賦值 mpvs.add(field.getName(), mpvs.getPropertyValue(alias).getValue()); // 跳出循環防止取其它別名 break; } } } }}
4.注冊到spring中
/** * 為了獲得context需要實現ApplicationContextAware接口 * @author lw */@Configurationpublic class WebmvcConfig implements ApplicationContextAware { @Autowired private RequestMappingHandlerAdapter adapter; private ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext=applicationContext; } /** * 將自定義的processor添加到adapter中 */ @PostConstruct protected void injectSelfMethodArgumentResolver() { List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); argumentResolvers.add(new AliasModelAttributeMethodProcessor(this.applicationContext)); argumentResolvers.addAll(adapter.getArgumentResolvers()); adapter.setArgumentResolvers(argumentResolvers); }}
補充知識:springboot - mybatis - 下劃線與駝峰自動轉換 mapUnderscoreToCamelCase
以前都是在mybatis.xml中來配置,但是spring boot不想再用xml配置文件。網上搜尋了好久,才找到設置辦法:
sessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
db配置文件源碼:
package com.vip.qa.vop.config;import com.alibaba.druid.pool.DruidDataSource;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.annotation.MapperScan;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;import java.util.Properties;/** * Created by danny.yao on 2017/10/25. */@Configuration@MapperScan(basePackages = VOPDataSourceConfig.PACKAGE, sqlSessionFactoryRef = 'vopSqlSessionFactory')public class VOPDataSourceConfig { static final String PACKAGE = 'com.vip.qa.vop.mapper.vop'; @Value('${vop.datasource.url}') private String dbUrl; @Value('${vop.datasource.username}') private String dbUser; @Value('${vop.datasource.password}') private String dbPassword; @Value('${vop.datasource.driver-class-name}') private String dbDriver; @Bean(name = 'vopDataSource') @Qualifier @Primary public DataSource vopDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(dbDriver); dataSource.setUrl(dbUrl); dataSource.setUsername(dbUser); dataSource.setPassword(dbPassword); return dataSource; } @Bean(name = 'vopSqlSessionFactory') @Qualifier @Primary public SqlSessionFactory vopSqlSessionFactory(@Qualifier('vopDataSource') DataSource scepDataSource) throws Exception { final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); sessionFactoryBean.setDataSource(scepDataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sessionFactoryBean.setMapperLocations(resolver.getResources('classpath:/mybatis/vop/*.xml')); sessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); return sessionFactoryBean.getObject(); }// @Bean(name = 'vopTransactionManager')// @Qualifier// public DataSourceTransactionManager testDataTransactionManager() {// return new DataSourceTransactionManager(vopDataSource());// }}
以上這篇為spring get請求添加自定義的參數處理操作(如下劃線轉駝峰)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. 使用Python webdriver圖書館搶座自動預約的正確方法2. SpringBoot整合Redis的步驟3. ASP.NET MVC使用jQuery ui的progressbar實現進度條4. Python3 json模塊之編碼解碼方法講解5. 在線php代碼縮進、代碼美化工具:PHP Formatter6. android H5本地緩存加載優化的實戰7. PHP如何開啟Opcache功能提升程序處理效率8. PHP程序員簡單的開展服務治理架構操作詳解(二)9. 詳解如何使用Net將HTML簡歷導出為PDF格式10.排行榜使用Python webdriver圖書館搶座自動預約的正確方法 1. android H5本地緩存加載優化的實戰 2. ASP.NET MVC使用jQuery ui的progressbar實現進度條 3. 詳解如何使用Net將HTML簡歷導出為PDF格式 4. 5. PHP程序員簡單的開展服務治理架構操作詳解(二) 6. PHP如何開啟Opcache功能提升程序處理效率 7. SpringBoot整合Redis的步驟 8. Python3 json模塊之編碼解碼方法講解 9. IntelliJ IDEA設置自動提示功能快捷鍵的方法 10. 在線php代碼縮進、代碼美化工具:PHP Formatter

網公網安備