Spring MVC Ajax调用POST无法正常工作

时间:2017-10-26 09:20:10

标签: java jquery ajax jsp spring-mvc

我有一个表单,我将其转换为对象。我想将该对象传递到服务器上,GET ajax请求工作正常但是java方法中的对象是空的,然后我执行相同的请求但是POST请求并且它说错误404.不确定我是什么?做错了或做了什么,跟着很多例子,但它们似乎都不起作用。

获取请求

(Ajax电话)

$.ajax({
     type: "GET",
     url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
     contentType: 'application/json',
     dataType: 'json',
     data: { medicalHistoryDTO : medicalHistoryDTO },
     success: function(data) {
            console.log(data);
     }
});

(Object medicalHistoryDTO)

Object

(Java方法)

@RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.GET)
public @ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
    System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
    System.out.println(medicalHistoryDTO);

    return "WORKING FINE";  
}

(Eclipse控制台)

COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE
MedicalHistoryDTO [list=null, medicalHistorySignature=null]

(浏览器控制台) enter image description here

POST REQUEST

(Ajax电话)

$.ajax({
     type: "POST",
     url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
     contentType: 'application/json',
     dataType: 'json',
     data: { medicalHistoryDTO : medicalHistoryDTO },
     success: function(data) {
            console.log(data);
     }
});

(Java方法)

@RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.POST)
public @ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
    System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
    System.out.println(medicalHistoryDTO);

    return "WORKING FINE";  
}

(浏览器控制台)

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试更严格地指定路径

@RequestMapping(value="/{id}/saveMedicalQuestionnair", , method = RequestMethod.POST)
public @ResponseBody
String postEditMedical(MedicalHistoryDTO medicalHistoryDTO, @PathVariable("id") int id)

答案 1 :(得分:0)

继续使用POST并接收您需要使用@RequestBody标记

public @ResponseBody String postEditMedical(@RequestBody MedicalHistoryDTO medicalHistoryDTO)

您可以在我的代码中看到一个工作示例https://github.com/shakeelabbas1/webservice/blob/master/src/main/java/com/service/controller/ServiceRequestController.java

更新: 我也看到data: { medicalHistoryDTO : medicalHistoryDTO } 将其替换为data: medicalHistoryDTO