这是我的ajax代码,这里我发送json对象作为Request payload。
$(document).ready(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var address = $("#address").val();
$("#studentInsert").click(function() {
student.presonal_details = {
firstName: $("#firstName").val(),
lastName: $("#lastName").val(),
address: $("#address").val(),
}
$.ajax({
type: "post",
url: "http://localhost:8080/RestJersey/rest/jsonRequestReceiver/saveStudentDeta il",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(student.presonal_details),
success: function(data) {
console.log(data);
}
});
});
});
Java代码:
我想知道如何编写用于接收json对象的REST服务API代码。
@POST
@Path("/saveStudentDetail")
@Consumes(MediaType.APPLICATION_JSON)
public void saveStudentDetail() {
}
这是我的web.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>RestJersey</display-name>
<welcome-file-list>
<!-- <welcome-file>index1.html</welcome-file> -->
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
可能POJO班:
package com.rest.test.to;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class StudentDetailsTO {
private String firstName;
private String lastName;
private String address;
// getters and setters
}
答案 0 :(得分:1)
使用以下代码
@POST
@Path("/saveStudentDetail")
@Consumes(MediaType.APPLICATION_JSON)
public void saveStudentDetail(StudentDetailsTO student){
String fname= student.getFirstName();
String lname= student.getLastName();
String address= student.getAddress();
}