繁体   English   中英

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

[英]Not receiving ajax request in the Controller in Spring MVC application?

我正在尝试使用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对象的方式。

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

\n @RequestMapping(value =“/ addTask”,method = RequestMethod.POST,consume =“application / json”)\n  public @ResponseBody String addTask(@RequestBody Task task){...}\n\n

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

您正在使用@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');
        }
    }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM