In JSP file I have field to enter student's group and then pass this data to entity class GroupStudent (without getter and setter methods)
@Entity
@Table(name = "GroupStudent")
@NamedQueries({
@NamedQuery(name = "GroupStudent.getAllGroups", // get all groups
query = "select g from GroupStudent g"),
@NamedQuery(name = "GroupStudent.getGroupByName", // get group by name
query = "select g from GroupStudent g where g.groupStudentNumber = :name")
})
public class GroupStudent implements Serializable {
public GroupStudent() {}
public GroupStudent(String groupStudentNumber) {
this.groupStudentNumber = groupStudentNumber;
}
// table GroupStudent fields
private Long groupStudentId;
private String groupStudentNumber;
}
JSP
<label>Group</label>
<input id="groupStudentNumber"/>
<input type="submit" value="Add" onclick="addGroupAjax()" />
and ajax function to pass data to Spring Controller
function addGroupAjax() {
var groupStudentNumber = $('#groupStudentNumber').val();
$.ajax({
type: "POST",
url: "/IRSystem/addData.html",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{groupStudentNumber:" + groupStudentNumber + "}",
success: function(response) {
},
error: function(e) {
alert("Error" + e);
}
});
}
but it do not pass data to controller. The field of the entity is empty.
@RequestMapping(value = "/addData.html", method = RequestMethod.POST)
public @ResponseBody Student addNewGroup(@ModelAttribute(value = "group") GroupStudent group) {
System.out.println("Entered group: " + group.getGroupStudentNumber());
return new Student();
}
and another thing that i can not pass entity Student to ajax too. I added to Spring jars
jackson-core-asl-1.7.1 and jackson-mapper-asl-1.7.1 to be able to pass entity object to ajax. But it gave not result. When i try to pass data (to ajax) in Google Chrome I have a window with error Error[object Object]. I do not know why it happens. I would appreciate any information, thank you.
Your controller is not properly set up to accept the post. If you are posting a JSON body, you need to use the @RequestBody
annotation for your method parameter, like this:
@RequestMapping(value = "/addData.html", method = RequestMethod.POST)
public @ResponseBody Student addNewGroup(@RequestBody GroupStudent group) {
System.out.println("Entered group: " + group.getGroupStudentNumber());
return new Student();
}
This way, your JSON will be directly mapped to your GroupStudent
object.
您还需要通过将消耗= MediaType.APPLICATION_JSON_VALUE添加到@RequestMapping中,产生= MediaType.APPLICATION_JSON_VALUE来指定消耗媒体类型。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.