a76
a76

Reputation: 47

Update object using JSP form

If I pass an object to jsp page, how can I update its fields using setters and send it back?

If for example we have

public class Person {

    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And a controller

@RequestMapping(value = "/updatePerson", method = RequestMethod.GET)
public String showPerson(Model model) {
    Person person = new Person();
    person.setAge(23);
    person.setName("Jack");
    model.addAttribute("person", person);

    return "updatePerson";
}

And a jsp page

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<form:form modelAttribute="person">
    <form:input path="age"/>
    <input type="submit"/>
</form:form>

How to make this JSP page send as a result modified person Object, not new with only one field?

Upvotes: 2

Views: 2720

Answers (1)

Bewusstsein
Bewusstsein

Reputation: 1621

Add a method in the controller that handles the form submit:

@RequestMapping(value = "/updatePerson", method = RequestMethod.POST)
public String alterPerson(@ModelAttribute Person person) {
    // do stuff
}

Note the changes:

  • POST instead of GET: submitting a form by default uses POST-Requests.
  • @ModelAttribute automatically retrieves the submitted data and fills a Person object with it

With the form you have the name field will always be empty, though. Add another <form:input path="name"/> to fix that.

If you don't want to let users change their name, the Person object probably shouldn't be in your model at all; it depends on how these objects are persisted, though. You could use a separate object like this:

public class PersonChangeRequest {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

And use it as the @ModelAttribute like this:

@RequestMapping(value = "/updatePerson", method = RequestMethod.GET)
public String showPerson(Model model) {
    PersonChangeRequest person = new PersonChangeRequest();
    person.setAge(23);
    model.addAttribute("person", person);

    return "updatePerson";
}

@RequestMapping(value = "/updatePerson", method = RequestMethod.POST)
public String alterPerson(@ModelAttribute PersonChangeRequest personChangeRequest) {
    Person person = findPersonToChange(personChangeRequest);
    person.setAge(personChangeRequest.getAge());
}

Upvotes: 3

Related Questions