在Spring MVC应用程序的Controller中没有收到ajax请求?

时间:2016-06-21 04:44:36

标签: java jquery ajax spring spring-mvc

我正在尝试使用Spring MVC创建一个Task Reader。 我在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对象的方式。

3 个答案:

答案 0 :(得分:2)

consumes="application/json"
中设置

@RequestMapping
Chnage方法:

@RequestMapping(value = "/addTask", method = RequestMethod.POST,consumes="application/json")
 public @ResponseBody String addTask(@RequestBody Task task) {...}

答案 1 :(得分:0)

您是否在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>

答案 2 :(得分:0)

您正在使用 @ResposeBody 而非 @RequestParam ,或者您没有正确使用json。

或@ResposeBody与多个Json绑定

绑定
  1. https://stackoverflow.com/a/37958883/5150781
  2. https://stackoverflow.com/a/21689084/5150781
  3. 这样做....

    /*
     * 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 Code

    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');
            }
        }); 
    
相关问题