【问题标题】:JSON Posting to Spring-MVC, Spring is not seeing the dataJSON 发布到 Spring-MVC,Spring 没有看到数据
【发布时间】:2012-06-01 18:39:09
【问题描述】:

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

这是我的 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");
         }
         });

};

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

【问题讨论】:

    标签: ajax json spring spring-mvc


    【解决方案1】:

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

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

    另外,删除 URL 路径中的 .htm。 htm 是某种请求类型覆盖。使用 .htm 指定 Web 服务器将请求作为经典 html 请求处理。使用 .json 将向网络服务器指定该请求期望作为 json 请求进行处理。

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 2018-02-28
      • 2012-10-03
      • 2013-10-25
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多