Reputation: 1281
I've been studying Spring for a week or so but I feel like I am missing something in regards to form handling.
For example, If I have a form that allows entering of Student
data, and I have a Student
bean defined like so:
public class Student {
private Integer age;
private String name;
private Integer id;
// and other getters and setters
}
Then I have a form:
<form:input path="name" />
<form:input path="age" />
<form:input path="id" />
and a Controller method that processes that post request:
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@ModelAttribute Student student) {
//do stuff
}
What If I want to create a custom form that is not directly adding "Student" that contains all the fields for each attribute that Student
has, but instead a custom form with some convoluted fields that looks nothing like the Student
we defined in the Model. For example:
<form:input path="age" />
<form:input path="firstname" />
<form:input path="lastname" />
Note that firstname
and lastname
properties both do not exist in the Student
class definition. I could concatenate these two values and put it in name
.
For this case, do I have to create a new bean class to define the attributes of that form? This seems kind of redundant to me.
And is this, ViewModel thing, a solution?
Upvotes: 2
Views: 438
Reputation: 148890
You can ask Spring to automagically bind request parameters to fields of a model attribute, or you can do everything by hand. The classical way, would be to have a form bean that has the same fields as the HTML form, and let Spring populate it, then you build your object from that form bean. Unless you have good reasons for it, my advice is to tick to that method that cleanly decouples the view part (the form + the form bean) from the model part (your model bean)
But you also have other options :
@RequestParameter("firstname")
, etc. annotated parameters and manually use them in your model object : you do by hand what Spring gives you for free but get full controlUpvotes: 1
Reputation: 48256
Create a "form-backing object", ie a class specific to your form. Copy the values from this FBO to your entity class.
It's not redundant if your form is not the same as your db entity.
If there are lots of fields, use a tool like Dozer to automate this.
Storing age and full name in the database is a bad idea though. Storing birth date and first name/last name is better.
Upvotes: 1
Reputation: 545
In this case you can form a JSON object with only the required fields and send it as a request body to the controller.
At client side- On click of a save button, frame the json and send as post request
At server side use-
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@RequestBody Student student) { }
Upvotes: 1