【问题标题】:How to pass @ModelAttribtue to Controller and call POST method to insert the data in spring mvc using ajax call如何将@ModelAttribtue 传递给Controller 并调用POST 方法以使用ajax 调用将数据插入spring mvc
【发布时间】:2017-09-06 11:34:54
【问题描述】:

我正在使用 jstl,我需要在从控制器插入 jsp 时取回 id。为了实现这一点,我正在使用 ajax,但无法传递表单的 modelAttribute。

JSP

<form:form method="POST" action="addCountry.html" name="form" modelAttribute="countryMaster" id="addCountryForm">
    <div class="box-body">
        <div class="row">
            <div class="col-md-6">
                <div class="form-group has-feedback" id="countryNameDiv">
                    <form:label path="countryName" for="countryName">Country Name</form:label>
                        <form:input placeholder="Enter country Name" path="countryName"
                            class="form-control" name="countryName"
                            value="${countryMaster.countryName}" required="true"
                            data-error="country Name cannot be empty" />
                            <form:errors path="countryName" cssClass="text-red" />
                            <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="box-footer">
        <form:button type="button" onclick="window.location.reload()" class="btn pull-left btn-primary">Clear</form:button>
        <div class="pull-right">
            <button onclick="submitTheForm()" class="btn btn-primary">Add Country</button>
            &nbsp;&nbsp;&nbsp;&nbsp;<a href="" class="btn pull-right btn-primary">Cancel</a>                    
        </div>
    </div>
</form:form>

AJAX

function submitTheForm(){
var value = $("#addCountryForm").serialize();
$.ajax({
    type : "post",
    url : 'addSaveCountry.html',
    dataType: "json"
    data : {
        countryMaster : value
    },
    success: function(result){
        console.log(result);
        if(resule.localeCompare("Some exception occured, try again.") == 0) {
            /**
            *   Give a div where you display this message
            **/
        } else if(result.localeCompare("New Country Inserted")) {
            var alert = "<div class=\"alert alert-success alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">x</span>";
            alert += "</button>";
            alert += "<strong>"+result+"!</strong>";
            alert += "</div>";
            var informationDiv = alert + "<br>";
            document.getElementById("informationDiv").innerHTML = informationDiv;
        } else {
            var alert = "<div class=\"alert alert-success alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">x</span>";
            alert += "</button>";
            alert += "<strong>"+result+"!</strong>";
            alert += "</div>";
            var informationDiv = alert + "<br>";
            document.getElementById("informationDiv").innerHTML = informationDiv;
        }
    }
});}

控制器代码

@RequestMapping(value="/addSaveCountry", method = RequestMethod.POST)
public @ResponseBody String addCountryPost(@Validated @ModelAttribute("countryMaster") Country country, BindingResult result){
try {
    if (result.hasErrors()) {
        Gson gson = new Gson();
        String json = gson.toJson("Some exception occured, try again.");
        return json;
    }
    int companyId = 1;
    country.setCompanyId(companyId);
    String createdBy, lastUpdatedBy;
    createdBy = "IN129";
    lastUpdatedBy = "IN129";
    country.setCreatedBy(createdBy);
    country.setLastUpdatedBy(lastUpdatedBy);
    java.sql.Timestamp curTime = new java.sql.Timestamp(new java.util.Date().getTime());
    country.setCreatedDate(curTime);
    country.setLastUpdatedDate(curTime);
    boolean status = countryService.addorupdateCountry(country);
    if (status == true) {   
        Gson gson = new Gson();
        String json = gson.toJson("New Country Inserted");
        return json;
    } else {
        Gson gson = new Gson();
        String json = gson.toJson("New Country Insertion Failed, Try Again Later");
        return json;
    }
}}

当我运行它并尝试插入时,我得到了
“HTTP 状态 405 - 不支持请求方法 'POST'”
消息 - 不支持请求方法 POST
描述 - 请求的资源不允许指定的 HTTP 方法。

提前致谢。

【问题讨论】:

    标签: ajax spring jsp


    【解决方案1】:

    从 html 后缀更改您的 URL:

    url : 'addSaveCountry.html',
    

    到RequestMapping的路径

    url : '/addSaveCountry',
    

    也改为类型:“POST”(大写)

    【讨论】:

    • 如果我从 url 中删除 .html,请求不会到达控制器,但是如果我在 url 中保留 .html 并将帖子从小写更改为大写,则值到达控制器但名称为 null 并显示相同的错误页面。
    • 使用 fiddler 检查请求正文中的内容,并检查正文是否可以映射到 Country 类,我认为 url 应该是“/addSaveCountry”,因为您的请求映射具有价值="/addSaveCountry"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 2020-11-22
    • 1970-01-01
    • 2017-12-26
    • 2018-09-01
    相关资源
    最近更新 更多