springmvc总结(配置传递参数去除前后空格、参数绑定时处理日期)

摘要:
importorg.springframework.core.converter.converter.converter;/***自定义转换器删除<}}之前和之后的空格catch(Exceptione){//TODO;}}}}returnnull;}2.在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"}


---

免责声明:文章转载自《springmvc总结(配置传递参数去除前后空格、参数绑定时处理日期)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇龙芯 loongnix20 rc2 初体验TableView之表头、表尾,区头、区尾!下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

java中远程http文件上传及file2multipartfile

    工作中有时会遇到各种需求,你得变着法儿去解决,当然重要的是在什么场景中去完成。 比如Strut2中file类型如何转换成multipartfile类型,找了几天,发现一个变通的方法记录如下(虽然最后没有用上。。): 1 private static MultipartFile getMulFileByPath(String picPath) {...

ARCore中四元数的插值算法实现

ARCore中四元数差值算法: 其中t的取值范围为[0, 1],当 t = 0 时,结果为a;当t = 1 时,结果为b。 1   public static Quaternion makeInterpolated(Quaternion a, Quaternion b, float t) { 2 Quaternion out = new...

LoadRunner系列之—-01 接口压力测试脚本

 LoadRunner中一般用如下函数进行接口测试: <一>. http或soap协议下的get请求接口,样例如下: web_url("integrated_query.jsp", "URL=http://{UrlAddress}/pcis/policy/query/integrated_query.jsp?CASOPDPT=00&...

网站日志流量分析系统之数据清洗处理(离线分析)

  网站日志流量分析系统之(日志收集)已将数据落地收集并落地至HDFS,根据网站日志流量分析系统中架构图,接下来要做的事情就是做离线分析,编写MR程序或通过手写HQL对HDFS中的数据进行清洗;由于清洗逻辑比较简单,这里我选择用Hive来对HDFS中的数据进行清洗(当然也可以用MR来清洗)。数据清洗处理过程相对较长,所以:Be patient,please...

Django——缓存机制

一、缓存介绍 缓存就是将常用的一些数据保存在内存或者们擦车中,在一定时间内,如果有请求访问这些数据的时候,则不用去服务器操作数据库渲染,直接缓存中获取,节约时间,增加访问速度,环节服务器压力 二、Django中的6种缓存方式 开发调试缓存 内存缓存 文件缓存 数据库缓存 Memcache缓存 Memcache缓存 三、Django缓存配置 1.2.1...

WebAPI客户端

封装WebAPI客户端,附赠Nuget打包上传VS拓展工具 一、前言 上篇《 WebAPI使用多个xml文件生成帮助文档 》有提到为什么会出现基于多个xml文件生成帮助文档的解决方案,因为定义的模型可能的用处有: 1:单元测试 2:其他项目引用(可能以Nuget包的形式) 3:WebAPI客户端(封装的HttpClient及WebAPI接口调用,其实包含...