简体   繁体   中英

Ajax JQuery to Spring @RequestBody? How do I pass data?

Ajax JQuery to Spring @RequestBody? How do I pass data? I being doing spring for sometime now with passing form fields but I am working on a new system and we would like to use Ajax and RESTful to pass data. My controller looks like the sample one below but can someone please me with the ajax call to post it?? how do I post to the Spring controller and put the data in the body

@RequestMapping(method=RequestMethod.PUT, value="/employee/{id}")
public ModelAndView updateEmployee(@RequestBody String body) {
        Source source = new StreamSource(new StringReader(body));
        Employee e = (Employee) jaxb2Mashaller.unmarshal(source);
        employeeDS.update(e);
        return new ModelAndView(XML_VIEW_NAME, "object", e);
    }

When using REST, it's important to understand the distinction between the different HTTP methods. PUT generally means that you're going to create a new collection or replace an existing one. POST generally means that you're adding a record to a collection. The main difference between the two is that PUT is idempotent, which means that repeating the same operation repeatedly doesn't change the state of the server.

In your code below, you're method is called "updateEmployee", which implies you're replacing a collection with a new one. Thus, PUT is the most appropriate HTTP Method to use in this scenario. However, you have a bug in your code. You didn't define the "id" in the parameter list:

// Added String id as a PathVariable
@RequestMapping(method=RequestMethod.PUT, value="/employee/{id}")
public ModelAndView updateEmployee(@RequestBody String body, @PathVariable String id) {   

        // You really don't need to do this. The Spring Framework can deserialize
          // objects for you. However, one issue at a time ;)
           // also, changed e to "employee" so the variable has a better name.
        Source source = new StreamSource(new StringReader(body));
        Employee employee = (Employee) jaxb2Mashaller.unmarshal(source);

        employeeDS.update(employee);
        return new ModelAndView(XML_VIEW_NAME, "object", employee);
}

To make the request to the server, use jQuery AJAX:

$.ajax({
  url: "/employee/2?t="+new Date().getTime(),
  contentType: 'application/x-www-form-urlencoded',
  type: "PUT",
  data: dataString,
  context: document.body,
  success: function(e){
          alert(e);                    
  },
      error: function(jqXHR, textStatus, errorThrown) {
          alert(" + textStatus + " : " + errorThrown);
      } 
});

dataString is a string representation of your data. You can either serialize the form, use JSON, or send a url-encoded form. Without seeing more code and more error messages in your question, it's unclear how you're representing your data when attempting to send it to the server. If you start here and fix the above errors in your Java code, this should get you past this specific error.

Another way to submit data to your REST method, just for testing, is to use a standard form, but use method="PUT", since that's what you're using in Spring:

<form name="test" action="/employee/2" method="PUT">
    <input type="text" name="firstname" />
    <input type="text" name="lastname" />
    <input type="submit" name="submit" value="submit" />
</form>

This will use application/x-www-form-urlencoded. If you're unable to deserialize that, then try using JSON instead. Good luck!

Hope gives you a start!


$.ajax({
    contentType : "application/json",
    dataType : 'json',
    type : "PUT",
    url : targetUrl,
    data : $(this).serializeObject(), //json serialization (like array.serializeArray() etc)
    async : false,
    success : function(data) {
       // response
    },
    error : function(request, status, error) {
       // any errors
    }
});

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