我是使用RESTful API的新手,我不知道为什么会显示此错误。 我通过jQuery发布值。我还需要做点什么吗?这是我的jQuery代码:
更新:现在显示 405(方法不允许)
$(document).ready(function(){
$("#patsubmit").click(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var mobileNumber = $("#mobileNumber").val();
var emailId = $("#emailId").val();
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '", "emailId":"' + emailId+'"}';
console.log(dataString);
if(firstName=='' )
{
alert("nothing in it");
}
else
{
$.ajax({
type: 'POST',
url : '/geniedoc/api/patient/register',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'}
success: function(){ // Uncaught SyntaxError: Unexpected identifier
console.log();
}
});}
return false;
});
});
这是我的Java API。 MAIN_PATIENT
= api/patient
和RestURIConstants.REGISTER
= register
@RestController
@RequestMapping(value = RestURIConstants.MAIN_PATIENT)
public class PatientRestController extends AbstractController implements RestURIConstants, GenieDocConstants{
private static final Logger logger = Logger.getLogger(UserRestController.class);
@RequestMapping(value = RestURIConstants.REGISTER, method = RequestMethod.POST, consumes ="application/json")
public @ResponseBody ModelMap registerPatient(HttpServletRequest request, @RequestBody PatientVo patientVo){
logger.info("registerPatient : Start");
long startTime = System.currentTimeMillis();
ModelMap map = new ModelMap();
PatientVo patVo;
try {
if(patientVo.getFirstName() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_FIRST_NOT_EMPTY));
} else if(patientVo.getEmailId() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
} else if(patientVo.getEmailId() == "") {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
} else if (patientVo.getMobileNumber() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_MOBILE_NOT_EMPTY));
} else {
patVo = this.patientManagementService.provisionPatient(patientVo);
if (patVo != null) {
map.addAttribute("patientId", patVo.getEmailId());
map.addAttribute(STATUS_CODE, SUCCESS_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(SUCCESS_STATUS_CODE_REGPATIENT));
} else {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REG);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REG));
}
}
} catch (MongoDBDocumentNotFoundException e) {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE,this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
logger.error("Error : " + e.getMessage());
//e.printStackTrace();
} catch (UserAreadyExsistException e) {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
logger.error("Error : " + e.getMessage());
//e.printStackTrace();
}
logger.debug("Exit: Total Time Taken: "+ (System.currentTimeMillis() - startTime));
return map;
}
答案 0 :(得分:2)
您需要将内容类型标题设置为 application / json
$.ajax({
type: 'POST',
url: '/geniedoc/api/patient/register',
data: dataString,
headers: {
'Content-Type':'application/json'
}
.....
}
在您定义的spring控制器中,只接受MIME类型 application / json 的内容。因为标准内容类型text / plain,Spring控制器不接受您的请求并发送回状态代码415(不支持媒体类型)
编辑:如上所述,用户6409738,您需要以json格式发送数据。否则,Spring Controller将导致解析正文的异常。
例如Yagnesh Agola发布的解决方案
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":' + emailId+'"}';
这取决于您的PatientVo Class的样子
答案 1 :(得分:0)
您从客户端发送到服务器的数据不是JSON格式。
var dataString = 'firstName='+ firstName + '&lastName=' + lastName + '&mobileNumber=' + mobileNumber + '&emailId=' + emailId;
以上行用于将数据字符串发送到不是JSON格式的服务器,它是简单的查询字符串。
您可以使用JSON格式转换上述字符串
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":"' + emailId+'"}';
OR
您可以使用以下代码直接以JSON格式提交表单数据。
var formData = JSON.stringify($("#myForm").serializeArray());
答案 2 :(得分:-1)
$.ajax({ type : "POST", contentType : 'application/json', url : "/geniedoc/api/patient/register", data : JSON.stringify({"param1" : "param1", "param2":2}) })
因为你在springMVC控制器中使用 @RequestBody ,然后SpringMVC将使用 RequestResponseBodyMethodProcessor 转换参数,该参数使用默认转换器来解析参数。默认转换器列表是:
public RequestMappingHandlerAdapter() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316
this.messageConverters = new ArrayList<HttpMessageConverter<?>>(4);
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(stringHttpMessageConverter);
this.messageConverters.add(new SourceHttpMessageConverter<Source>());
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
对于您的情况,期望使用 MappingJackson2HttpMessageConverter 来解析参数。这里是MappingJackson2HttpMessageConverter的定义,它需要MediaType of application / json
public MappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
super(objectMapper, MediaType.APPLICATION_JSON_UTF8,
new MediaType("application", "*+json", DEFAULT_CHARSET));
}