Spring MVC learning summary (6): custom type conversion

       Any data types submitted in the form are all string types. After receiving the request in the background, the HandlerAdapter inside the Spring framework will perform data type conversion by default. But if it contains non-basic data types, such as the user's birthday in the user form, the HandlerAdapter cannot automatically convert the String type to the Date type. At this time, it is necessary to implement the Converter interface to assist Spring MVC to complete the data type conversion. First look at the effect of not using a custom type converter, the implementation steps are as follows:

(1) Create an entity class

public class User {
    private String name;
    private String password;
    private Integer age;
    private Date birthday;

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}

(2) Add user form in index.jsp.


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/user/login">
    姓名:<input type="text" name="name"><br>
    密码:<input type="text" name="password"><br>
    年龄:<input type="text" name="age"><br>
    生日:<input type="text" name="birthday"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

(3) Create the UserController class

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public String login(User user){
        System.out.println(user);
        return "success";
    }
}

(4) Success.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>SUCCESS</h3>
</body>
</html>

Start the project, enter the information on the page and click Submit. At this time, the birthday format entered on the page is 1997/12/12.

But if you enter 1997-10-10, the data will be encapsulated incorrectly, as follows:

 

Spring MVC provides Converter<S, T>, an interface that can convert one data type to another data type, where S represents the source type and T represents the target type . The realization process is as follows:

(1) Custom type converter to implement interface

public class MyDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        if(s == null){
            throw new RuntimeException("日期数据为空");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try{
            return df.parse(s);
        }catch (Exception e){
            throw new RuntimeException("日期数据转换失败");
        }
    }
}

(2) Add configuration in springmvc.xml

<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>
    <!--  注册自定义类型转换器  -->
    <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.yht.example1.utils.MyDateConverter"></bean>
            </set>
        </property>
    </bean>

At this time, enter 1997-12-12 on the page, and the operation is successful, as follows:

Note that there are two formats: 1997/12/12 and 1997-12-12. As mentioned earlier, the Spring MVC framework can automatically map 1997/12/12 to the date type of the pojo object, but cannot map 1997-12-12, so we use a custom type converter to handle the 1997-12-12 Format input data, but when the custom type converter works, the original 1997/12/12 format date cannot be mapped successfully. I briefly checked the source code of ConversionServiceFactoryBean and found that the problem lies in the set method, as follows:

 I personally think that the converter attribute is assigned through property in the configuration file, and the type conversion operation performed by default in the original Spring MVC is overwritten. The jar packages in the spring mvc I use are all version 4.2.3. Whether the implementation of this class is different in the lower version, it remains to be further studied in the future.

At present, I have checked a lot of blogs and have not found a solution that can use these two formats at the same time. If a small partner finds it, you can comment and make progress together.

Regarding date formatting, there is an annotation @DateTimeFormat(pattern = "yyyy-MM-dd") in Spring MVC. You only need to add this annotation to the birthday attribute of the User class. If the pattern is yyyy- MM-dd supports the 1997-12-12 format. If the pattern is yyyy/MM/dd, 1997/12/12 is supported.

 

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113574318
Recommended