Failed to convert property value of type ‘java.lang.String‘ to required type ‘int‘ for property(代码片段

Posted 夜中听雪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Failed to convert property value of type ‘java.lang.String‘ to required type ‘int‘ for property(代码片段相关的知识,希望对你有一定的参考价值。

问题概述:
前端由ajax传递参数,后端由User对象接收所有参数。
String->int。
String->Date。

报错

报错时提示

Field error in object 'user' on field 'type': rejected value []; codes [typeMismatch.user.type,typeMismatch.type,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.type,type]; arguments []; default message [type]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'type'; nested exception is java.lang.NumberFormatException: For input string: ""]]

Field error in object 'user' on field 'createTime': rejected value []; codes [typeMismatch.user.createTime,typeMismatch.createTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.createTime,createTime]; arguments []; default message [createTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]

报错时代码

前端-html

<div class="modal-body">
    <form>
        <div class="form-group">
            <label class="col-form-label">账号:</label>
            <input type="text" class="form-control" id="username" required>
        </div>
        <div class="form-group">
            <label class="col-form-label">密码:</label>
            <input type="text" class="form-control" id="password" required>
        </div>
        <div class="form-group">
            <label class="col-form-label">用户类型:</label>
            <input type="text" class="form-control" id="type">
        </div>
        <div class="form-group">
            <label class="col-form-label">注册时间:</label>
            <input type="text" class="form-control" id="createTime">
           <!-- <input type="date" class="form-control" id="createTime" name="createTime"
                   th:value="${user!=null?#dates.format(user.createTime,'yyyy-MM-dd'):#dates.format(new java.util.Date().getTime(),'yyyy-MM-dd')}"/>-->
        </div>
    </form>
</div>

前端-js

$(function(){
    $("#publishBtn").click(publish);
});

function publish() {
    $("#publishModal").modal("hide");

    // 获取标题和内容
    var username = $("#username").val();
    var password = $("#password").val();
    var type = $("#type").val();
	/* 
	var type = Number($("#type").val());
	*/
    var createTime = $("#createTime").val();

    // 发送异步请求(POST)
    $.post(
        CONTEXT_PATH + "/admin/add",
        {
            "username":username,
            "password":password,
            "type":type,
            "createTime":createTime,

        },
        function(data) {
            data = $.parseJSON(data);
            // 在提示框中显示返回消息
            $("#hintBody").text(data.msg);
            // 显示提示框
            $("#hintModal").modal("show");
            // 2秒后,自动隐藏提示框
            setTimeout(function(){
                $("#hintModal").modal("hide");
                // 刷新页面
                if(data.code == 0) {
                    window.location.reload();
                }
            }, 2000);
        }
    );
}

后端Controller

@Controller
@RequestMapping("/admin")
public class UserCurdController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserCurdService userCurdService;
    
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(User user
    /*@RequestBody User user*/
    /*@DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime*/
    /*@RequestBody Map<String,Object> user*/) {

        if (hostHolder.getUser() == null) {
            return CommunityUtil.getJSONString(403, "你还没有登录哦!");
        }

        Map<String, Object> map = userCurdService.insertUser(user);
        if (map == null || map.isEmpty()) {
            return CommunityUtil.getJSONString(0, "增加成功!");
        } else {
            return CommunityUtil.getJSONString(0, "增加失败!",map);
        }
    }
}

解决

问题在于js处传递给后台的都是String类型,但User实体类有:int type、Date createTime。于是使用springboot框架时int type和Date createTime没有处理好。

1、
对于Date createTime,可以通过在实体类时间字段加注解即可。

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date createTime;

为了让用户不要胡乱输入,可以给"前端-html"加日历控件,代替输入框:

<input type="date" class="form-control" id="createTime" name="createTime"
                                           th:value="${user!=null?#dates.format(user.createTime,'yyyy-MM-dd'):#dates.format(new java.util.Date().getTime(),'yyyy-MM-dd')}"/>

2、
对于int type,在"前端-js"里对其进行类型转换,String->int。

    var type = Number($("#type").val());

其他

POST、GET、@RequestBody和@RequestParam区别_Hello World-CSDN博客_@requestbody

以上是关于Failed to convert property value of type ‘java.lang.String‘ to required type ‘int‘ for property(代码片段的主要内容,如果未能解决你的问题,请参考以下文章

Failed to convert from type [java.lang.Object[]] to type HashMap<String, String>的解决方法

python2.7运行出现的Warning: UnicodeWarning: Unicode equal comparison failed to convert both arguments to

关于在2.7中出现 "UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode

spring mvc出现 Failed to convert property value of type 'java.lang.String' to required type &#

Failed to convert value of type ‘java.lang.String‘ to required type ‘java.util.Date‘;

springboot 提交时间字符串报错 Failed to convert property value of type ‘java.lang.String‘ to required ‘Date‘