springmvc總結(配置傳遞參數去除前后空格、參數綁定時處理日期)


1.屬性為Integer時,前台表單不填,默認為null;屬性為String,前台表單不填,默認為"";
2.屬性為Integer時,前台表單填空格,model封裝為null;屬性為String,前台表單填空格,model封裝為"  ";
3.屬性為Integer,后台model封裝時【去除】前后空格;屬性為String,后台model封裝時【不去除】前后空格;
4.屬性為Integer,表單填非數字,報錯http400(Bad Request)

 

錄:

一、springmvc配置傳遞參數去除前后空格
二、使用filter攔截參數去掉兩端的空格(資料+親測解決)
三、springmvc+jackson處理date
四、前端日期字符串轉換為java.util.date的三種方法
五、日期轉換的處理(全局和局部)

一、springmvc配置傳遞參數去除前后空格    <--返回目錄

來自:https://blog.csdn.net/Archer_M/article/details/79884228

1. 創建自定義轉換器類

package com.java1234.test;
import org.springframework.core.convert.converter.Converter;
/**
 * 自定義轉換器 去掉前后空格 <S, T> : S 頁面上類型 T : 轉換后的類型
 */
public class CustomConverter implements Converter<String, String> {
    // 去掉前后空格
    @Override
    public String convert(String source) {
        // TODO Auto-generated method stub
        try {
            if (null != source) {
                source = source.trim();
                if (!"".equals(source)) {
                    return source;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception } return null; } }
        }
        return null;
    }
}


2. 在springmvc文件中進行配置

<!-- 處理器 映射器  適配器 -->
<mvc:annotation-driven conversion-service="conversionService"/>

<!-- Converter轉換器工廠  
    注: 需要在 適配器 中進行配置 --> 
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
    <!-- 日期 --> 
    <!-- 去掉前后空格 --> 
    <property name="converters"> 
        <list> 
            <bean class="cn.jay.common.conversion.CustomConverter"></bean>
        </list>
    </property> 
</bean>

 

二、使用filter攔截參數去掉兩端的空格(資料+親測解決)    <--返回目錄

https://blog.csdn.net/xiaoyu19910321/article/details/52838828

 

三、springmvc+jackson處理date    <--返回目錄

參考資料:https://www.cnblogs.com/woshimrf/p/5189435.html

MappingJacksonHttpMessageConverter主要通過ObjectMapper來實現返回json字符串。這里我們繼承該類,
注冊一個JsonSerializer<T>。然后在配置文件中注入自定義的ObjectMapper。

1.編寫子類繼承ObjectMapper

package com.demo.common.util.converter;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 解決Date類型返回json格式為自定義格式
*/
public class CustomJsonDateConverter extends ObjectMapper {
    public CustomJsonDateConverter(){
        CustomSerializerFactory factory = new CustomSerializerFactory();
        factory.addGenericMapping(Date.class, new JsonSerializer<Date>(){
            @Override
            public void serialize(Date value,JsonGenerator jsonGenerator,SerializerProvider provider)throws IOException {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                jsonGenerator.writeString(sdf.format(value));
            }
        });
        this.setSerializerFactory(factory);
    }
}



2.配置spring文件

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="customObjectMapper"></property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="customObjectMapper" class="com.demo.common.util.converter.CustomJsonDateConverter"></bean>



3.使用內置的日期格式化工具
    同樣是全局設置json響應的日期格式,但此方法可以和@JsonFormat共存,也就是說可以全局設置一個格式,
    特定的需求可以使用注解設置。

    * 配置spring文件:配置全局json的日期轉換格式

<mvc:annotation-driven>  
<!-- 處理responseBody 里面日期類型 -->  
    <mvc:message-converters>  
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
            <property name="objectMapper">  
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">  
                    <property name="dateFormat">  
                        <bean class="java.text.SimpleDateFormat">  
                            <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />  
                        </bean>  
                    </property>  
                </bean>  
            </property>  
        </bean>  
    </mvc:message-converters>  
</mvc:annotation-driven>


    * 配置特定的date

@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
public Date getBirth() {
    return birth;
}

 

四、前端日期字符串轉換為java.util.date的三種方法    <--返回目錄

解決SpringMVC Controller中接受日期格式發生400錯誤
https://blog.csdn.net/wangxueqing52/article/details/80536028?utm_source=blogxgwz0

    解決方法一:
        我們使用@DateTimeFormat(pattern="yyyy-MM-dd") 首先需要引入一個jar 包,否者是不能的:joda-time-2.1.jar

        然后在spring.xml中進行配置。首先需要在頭上面加上:
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        http://www.springframework.org/schema/mvc
              http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        (當然版本不同spring-mvc-3.0.xsd 寫法也不同)。

        頭加上之后,然后需要配置進行聲明:<mvc:annotation-driven></mvc:annotation-driven>  

        最后在你所需要的Date數據類型之上加上@DateTimeFormat(pattern="yyyy-MM-dd")即可
        ---------------------
        作者:默默的菜鳥--
        來源:CSDN
        原文:https://blog.csdn.net/qq_34160679/article/details/76401576
        版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
        

    方法二:Controller類中
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允許輸入空值,false:不能為空值
    }
    
    方法三:實現一個全局日期類型轉換器並進行配置
    spring3.1以前的配置
    https://blog.csdn.net/wangxueqing52/article/details/80536028?utm_source=blogxgwz0、
    spring3.1以后的配置
    https://blog.csdn.net/chenleixing/article/details/45156617
    https://blog.csdn.net/chenleixing/article/details/45190371

 

五、日期轉換的處理(全局和局部)    <--返回目錄

1.配置全局的json消息處理

// 自定義消息轉換器MappingJacson2HttpMessageConverter
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(fmt);
    return mapper;
}

   
    測試1:
        @ResponseBody轉換json時,效果:
        {"id":1,"name":"張三1","age":11,"date":"2019-01-13 22:20:47"}
        
    測試2:
        前台表單格式:2019-01-13 22:20:47。
        前台傳遞json數據,@RequestBody綁定數據,成功。
    
    測試3:
        前台表單格式:2019-01-13。
        前台傳遞json數據,@RequestBody綁定數據,失敗。
        
    測試4:
        前台表單提交格式:2019-01-13 22:20:47,失敗。
        因為傳遞的表單數據,所以需要配置StringToDateConverter。
        
2.自定義及配置全局的日期轉換器【StringToDateConverter】

/**
 * 增加字符串轉日期的功能
 * https://blog.csdn.net/fansili/article/details/78366874
 */
@PostConstruct
public void initEditableAvlidation() {

    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
    
    if(initializer.getConversionService() != null) {
        GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();           
        
        // 注冊自定義的StringtoDate的轉換器
        genericConversionService.addConverter(new StringToDateConverter());
    }
}


    測試5:
        前台表單提交格式:2019-01-13 22:20:47,成功。
        前台表單提交格式:2019-01-13,也成功。
        因為:轉換器中對傳遞的字符串進行了判斷
        if (source.length() == 10) {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        } else if (source.length() == 16) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        } else if (source.length() == 19) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else if (source.length() == 23) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        }
    
3.要想自定義json轉換時日期的格式,怎么辦?
    局部配置:在實體類字段上或getter方法上
    @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")
    private Date date;

    測試6:
        前台表單格式:2019-01-13或2019-01-13 aa:bb:cc.abc
        前台傳遞json數據,@RequestBody綁定數據,成功。

    並且,后台@ResponseBody轉換json時,效果:
    {"id":1,"name":"張三1","age":11,"date":"2019-01-13"}


 

---


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM