简体   繁体   中英

How to pass @ModelAttribtue to Controller and call POST method to insert the data in spring mvc using ajax call

I am using jstl and I need to get back the id upon insertion to jsp from controller. To achieve that I am using ajax and I am unable to pass the modelAttribute of the form.

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;
        }
    }
});}

Controller Code

@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;
    }
}}

When I run it and try to insert, I am getting
"HTTP Status 405 - Request method 'POST' not supported"
message - Request method POST not supported
description - The specified HTTP method is not allowed for the requested resource.

Thanks in advance.

Change your URL from html suffix :

url : 'addSaveCountry.html',

To Path of RequestMapping

url : '/addSaveCountry',

also change to type: "POST" (uppercase)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM