我的Controller中有一个简单的模型对象Person
,我想在 jQuery 中访问该对象。
我正在尝试将对象从Controller传递到 JSP 视图,然后从 JSP 中查看 jQuery 中的对象Javascript文件。
以下是代码:
Person.java
public class Person {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return 25;
}
public String getLastname() {
return "Ybarra";
}
}
控制器方法
@RequestMapping("/person")
public ModelAndView handleRequest() throws Exception {
Person person = new Person();
person.setName("Person's name");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(person);
ModelAndView modelAndView = new ModelAndView("person.jsp");
modelAndView.addObject("person", json);
return modelAndView;
}
person.jsp
//...
<body>
<h1>Person</h1>
<input type="hidden" id="person" value="${person}">
</body>
/...
Javascript文件
//...
var p = $('#person');
console.log(p);
console.log(p.lastname);
console.log(p.age);
// ...
问题是控制台为p.lastname
和p.age
输出未定义输出,但正确输出console.log(p).
的整个对象如何访问{{1 }和lastname
属性?
答案 0 :(得分:0)
您只能访问已创建的属性,并且未在age
bean类中创建lastname
和Person
属性,因此请更改Person
类如下图所示:
public class Person {
private String name;
private int age; //age property
private int lastname; //lastname property
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return 25;
}
public void setAge(int age) {
this.age = age;
}
public int getLastname() {
return "Ybarra";
}
public void setLastname(int lastname) {
this.lastname = lastname;
}
}