0

我正在开发一个项目,该项目将使用 Ajax 将 JSON 对象发布到 Springs-MVC。我一直在进行一些更改,并且达到了不再出现错误的地步,但是我没有看到在我需要的对象中发布到 Spring 的数据。

这是我的弹簧控制器。

@RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)
    public @ResponseBody JsonResponse addUser(@ModelAttribute(value="user") User user, BindingResult result ){
        JsonResponse res = new JsonResponse();

        if(!result.hasErrors()){
            res.setStatus("SUCCESS");
            res.setResult(userList);
        }else{
            res.setStatus("FAIL");
            res.setResult(result.getAllErrors());
        }

        return res;
    }

我放了一个断点,我的 USER 对象永远不会获取数据。接下来是我的 USER 对象的副本:

public class User {

    private String name = null;
    private String education = null;

    private List<String> nameList = null;
    private List<String> educationList = null;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEducation() {
        return education;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public List<String> getNameList() {
        return nameList;
    }
    public void setNameList(List<String> nameList) {
        this.nameList = nameList;
    }
    public List<String> getEducationList() {
        return educationList;
    }
    public void setEducationList(List<String> educationList) {
        this.educationList = educationList;
    }

现在对于执行 Ajax、JSON 发布的 javascript 代码:

function doAjaxPost() {  

      var inData = {};

      inData.nameList = ['kurt','johnathan'];
      inData.educationList = ['GSM','HardKnocks'];

      htmlStr = JSON.stringify(inData);
      alert(".ajax:" + htmlStr);


    $.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         url:  contexPath + "/AddUser.htm",
         data: inData,
         dataType: "json",
         error: function(data){
              alert("fail");
         },
         success: function(data){
              alert("success");
         }
         });

};

如果你能帮忙,请让我现在??我必须尽快让这个工作......谢谢

4

1 回答 1

3

您还需要在控制器中找到的 RequestMapping 注释中指定标头。

@RequestMapping(headers ={"Accept=application/json"}, value="/AddUser.htm", method=RequestMethod.POST)

Also, remove .htm in your URL path. htm is some kind of request type overide. Using .htm specifies the web server to handle the request as a classic html request. Using .json would specify to the webserver that the request expects to be handled as a json request.

于 2012-06-04T09:47:42.840 回答