【问题标题】:Not receiving ajax request in the Controller in Spring MVC application?在 Spring MVC 应用程序的控制器中没有收到 ajax 请求?
【发布时间】:2016-10-22 11:45:53
【问题描述】:

我正在尝试使用 Spring MVC 创建任务阅读器。 我在 Task 中有 3 个字段:id、Description 和 dueDate。

现在点击“添加按钮”,我正在尝试向 Spring 控制器发送 Ajax 调用。但我没有在服务器端收到请求。

下面是Ajax请求代码:

function doAjaxPost() {
    var id = $('#id').val();
    var desc = $('#description').val();
    var dueDate = $('#dueDate').val();
    var json = { "id" : id, "description" : desc, "dueDate": dueDate};
    $.ajax({
    type: "POST",
    contentType : "application/json",
    url: "/addTask",
    data : JSON.stringify(json),
    dataType : 'json',

    success: function(response){
    $('#info').html(response);
    },
    error: function(e){
    alert('Error: ' + e);
    console.log(e);
    }
    });
    }

以及控制器代码:

@RequestMapping(value = "/addTask", method = RequestMethod.POST)
    public @ResponseBody String addTask(@RequestBody Task task) {
        String returnText;
        System.out.println(task.getDescription() + " " + task.getDueDate());
        System.out.println(task);
        // taskList.add(task);
        returnText = "User has been added to the list. Total number of task are " + taskList.size();

        return returnText;
    }

我在 Chrome 控制台中收到以下错误消息。

服务器拒绝此请求,因为请求实体的格式不受所请求方法的请求资源支持。”

谁能指出我在哪里犯了错误?

更新:

我可以用另一种方式做到这一点:

@RequestMapping(value = "/addTask" , method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String addTask(@RequestBody String task){
        Gson gson = new Gson();
        Task t = gson.fromJson(task, Task.class);
        taskList.add(t);
        ObjectMapper mapper = new ObjectMapper();
        String jsontastList = gson.toJson(taskList);
        return jsontastList;
    }

但我仍然想知道我不需要将 json 显式转换为 Java 对象的方式。

【问题讨论】:

  • 能贴一下这个addTask(...)方法所在的控制器类吗?
  • 还要确认console是否有错误信息,请编辑代码并正确缩进
  • @Tahir 我已经添加了控制器类和 addTask() 方法。
  • 问题解决了吗? @VickyJain
  • 没有问题还是没有解决

标签: java jquery ajax spring spring-mvc


【解决方案1】:

设置

consumes="application/json"
@RequestMapping
将方法更改为: @RequestMapping(value = "/addTask", method = RequestMethod.POST,consumes="application/json") 公共@ResponseBody String addTask(@RequestBody 任务任务) {...}

【讨论】:

    【解决方案2】:

    你是否在 Spring 配置中配置了消息转换器?像这样:

    <mvc:message-converters>  
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
            <property name="objectMapper">  
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                </bean>  
            </property>  
        </bean>  
    </mvc:message-converters>
    

    您还应该添加 maven 依赖项,例如:

    <dependency>  
        <groupId>com.fasterxml.jackson.core</groupId>  
        <artifactId>jackson-databind</artifactId>  
        <version>2.5.3</version>  
    </dependency>
    

    【讨论】:

      【解决方案3】:

      您正在使用 @ResposeBody 而不是 @RequestParam 或者您没有正确获取 json。

      或通过@ResposeBody 绑定多个Json 查看

      1. https://stackoverflow.com/a/37958883/5150781
      2. https://stackoverflow.com/a/21689084/5150781

      这样做......

      /*
       * Mapping for Demographics And Profiling Question Filter
       */
      @RequestMapping (value = "/generalFilter")
      public void ageFilteration(@RequestParam Map <String,String> filterParams,HttpServletRequest request,HttpServletResponse response) throws IOException
      {
          //  System.out.println("Geographies in Controller :"+ filterParams.get("geographies"));
          List<FeasibilityBean> feasibilityList = feasibilityDao.getGeneralFeasibilityList(filterParams,request);
          //  System.out.println(" General Filter List Size:"+feasibilityList.size());
          response.getWriter().print(new Gson().toJsonTree(feasibilityList,new TypeToken<List<FeasibilityBean>>(){}.getType()));
      }
      

      }

      js代码

      var ages='',ageCond='',genders='',genderCond='';
      
          $.ajax({
              type: "POST",
              url : url,
              data : {ages:ages,ageCond:ageCond,genders:genders,genderCond:genderCond},
              beforeSend: function() { 
                  $(thisVar).find('i').addClass('fa-spin');
              },
              success : function(feasibilityJson){ 
      
              },
              error : function(data) {
                  alert(data + "error");
              },
              complete:function(){  
                  $(thisVar).find('i').removeClass('fa-spin');
              }
          }); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-30
        • 1970-01-01
        • 2011-10-20
        • 1970-01-01
        • 2017-02-12
        • 2020-08-06
        • 1970-01-01
        相关资源
        最近更新 更多