从jQuery访问Spring MVC模型对象

时间:2016-11-27 22:33:22

标签: javascript jquery spring jsp

我的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.lastnamep.age输出未定义输出,但正确输出console.log(p).的整个对象如何访问{{1 }和lastname属性?

1 个答案:

答案 0 :(得分:0)

您只能访问已创建的属性,并且未在age bean类中创建lastnamePerson属性,因此请更改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;
        }
    }