spring mvc 时间格式转换

在前后台传值时常常出现时间格式转换出错问题。

解决:jsp页面往 action 传值时出现的问题。

原因,jsp页面的时间格式是个字符串格式,后台是DATE格式,会出现格式不匹配

1、找个地方创建一个类让他实现 Converter接口,两个泛型代表,String类型转换成date类型

//Converter<S, T>
//S:source,需要转换的源的类型
//T:target,需要转换的目标类型
public class DateConverter implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		try {
			// 把字符串转换为日期类型
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
			Date date = simpleDateFormat.parse(source);

			return date;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 如果转换异常则返回空
		return null;
	}
}
2、配置  Converter

在spring mvc 的配置文件中添加配置

<!-- 配置注解驱动 -->
<!-- 如果配置此标签,可以不用配置... -->
<mvc:annotation-driven conversion-service="conversionService" />

<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<property name="converters">
		<set>
                        <!-- 这个类名是刚刚创建好的类的全路径 -->
	        	<bean class="cn.itcast.springmvc.converter.DateConverter" />
</set></property></bean>

解决:action往 jsp页面传值时出现的问题。

原因,jsp页面的时间格式是个字符串格式,后台是DATE格式,会出现格式不匹配

1、同样找个地方创建一个类

继承    JsonSerializer<Date>

package com.cn.config;

import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class viewObjectMapper extends JsonSerializer<Date>{

	  @Override  
	    public void serialize(Date value, JsonGenerator jgen, SerializerProvider arg2)  
	            throws IOException, JsonProcessingException {  
	        // TODO Auto-generated method stub  
	        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
	        String formattedDate = formatter.format(value);  
	        jgen.writeString(formattedDate);  
	          
	    }  

	
	 
	
}

2、在需要传递的实体类 参数的get方法上添加注解使用刚刚写好的类

注解一定要写在get方法上

public class UserInfo {  
    private String name;  
    private int id;  
    private Date birthday;  
      
    @JsonSerialize(using = viewObjectMapper.class)  
    public Date getBirthday() {  
        return birthday;  
    }  
  
    public void setBirthday(Date birthday) {  
        this.birthday = birthday;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
      
}  

猜你喜欢

转载自blog.csdn.net/SUNbrightness/article/details/80055573