Spring Portlet Jquery Ajax发布到Controller

时间:2015-06-18 17:46:41

标签: javascript jquery json spring-mvc spring-portlet-mvc

修改

startdate和enddate是POJO中的joda dateTime,我得到的错误是:

SystemOut     O 14:10:16.040 [WebContainer : 2] DEBUG org.springframework.beans.BeanUtils - No property editor [org.joda.time.DateTimeEditor] found for type org.joda.time.DateTime according to 'Editor' suffix convention
...
SystemOut     O Error::Failed to convert property value of type 'java.lang.String' to required type 'org.joda.time.DateTime' for property 'startTimestamp'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.joda.time.DateTime] for property 'startTimestamp': no matching editors or conversion strategy found

我也无法编辑Pojo并添加@DateTimeFormat,因为Pojos是从XSD生成的。我也尝试添加一个customObjectMapper,但没有任何作用。任何帮助将不胜感激。

原始问题:

我正在尝试提交表单并将数据发送到Controller方法。问题是ModelAttribute是空的,没有值。 Spring MVC Portlet + Jsp + Javascript + Jquery + Controller @ResourceMapping

段:

JSP:

<portlet:resourceURL id="addNewURL" var="addNewURL">
    </portlet:resourceURL>  

<form:form id="qmat_new_notification_form" action="#" method="POST" modelAttribute="dataObject">    
  ...
  <input type="text" class="date-picker" id="start_date">
  ...    
  <input type="submit" value="Save" class="button" onclick="addNew()">    
</form:form>

Jquery的:

function addNew() { 

            var dataObject = JSON.stringify({
                'startTime': $('#start_date').val(),
                'endTime': $('#end_date').val(),
                'description': $('#message').val(),
                'active': $('#status').val()
            });

            alert("data::"+dataObject);

            $.ajax({
                url: "<%=addNewURL%>",
                type: 'POST',
                contentType: 'application/json',
                data: dataObject
            }).done(function(json){         
alert("Success!");
//more logic    
            }).fail(function() {
                alert("OOPS!");
            });
        }

控制器:

    @ResourceMapping(value = "addNewURL")
        public void addNew(@ModelAttribute(value = "dataObject") Obj n,
                            BindingResult bindingResult, ResourceRequest request, ResourceResponse response, ModelMap model) {

            if (!bindingResult.hasErrors()) {
                System.out.println("a:::"+n.getDescription());
}

此getDescription为null。另外如果我使用request.getParameter(“description”)也是null。我错过了什么?请帮忙

1 个答案:

答案 0 :(得分:1)

您根本不需要使用JSON数据。

首先,避免使用dataObject的字符串化:

var dataObject = {...}; // no JSON.stringify call

其次,删除contentType: 'application/json',因为在这种情况下没有意义。

如果dataObject是键/值对且默认为contentType,则POST请求将正确构建。

要处理点击和提交事件,我建议jQuery点击并提交方法:

$("#submit").click(function (event) {
    addNew();
    event.preventDefault();
});
$("#submit").submit(function (event) {
    addNew();
    event.preventDefault();
});

我已经为这个问题创建了fiddle

请参阅jQuery.ajax文档。