SpringMVC中自定義類型轉換器

1.首先本身寫一個類型轉換器,實現org.springframework.core.convert.converter.Converter這個接口

@Component("studentConverter")
public class StudentConverter implements Converter<String, Student> {
    @Override
    public Student convert(String source) {
        if (source == null || source.isEmpty()) {
            return null;
        }
        String[] strings = source.split("-");
        if (strings.length != 3) {
            return null;
        }
        Student student = new Student();
        student.setSid(Long.valueOf(strings[0]));
        student.setName(strings[1]);
        try {
            student.setBirthday(DateUtils.parseDate(strings[2], "yyyy/MM/dd"));
        } catch (ParseException e) {
            student.setBirthday(null);
        }
        return student;
    }
}

Student類以下:java

public class Student implements Serializable {
    private Long sid;
    private String name;
    private Date birthday;

    public Long getSid() {
        return sid;
    }

    public void setSid(Long sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

2.配置SpringMVC配置文件:

<!--啓動MVC註解掃描功能,若是須要使用自定義的類型轉換器則須要配置conversion-service -->
    <mvc:annotation-driven conversion-service = "conversionService" />
<!--註冊自定義的類型轉換器-->
    <bean id = "conversionService" class = "org.springframework.context.support.ConversionServiceFactoryBean">
        <property name = "converters">
            <set>
                <ref bean = "studentConverter" />
            </set>
        </property>
    </bean>

3.測試代碼以下:

@RequestMapping(value = "studentConverter")
    public ModelAndView studentConterver(
            @RequestParam("student")
                    Student student, ModelAndView modelAndView) {
        System.out.println(student);
        modelAndView.addObject("msg", "Conterver Successful!");
        modelAndView.setViewName("success");
        return modelAndView;
    }

請求以下:spring

http://localhost:8080/SSMProjectMaven/hello/studentConverter.do?student=1-黃色-1994/09/03mvc

測試結果以下:app

相關文章
相關標籤/搜索