Used Spring MVC, sample code presented below:
The methods of the controller
/*
* Create a new object and initialize it.
*/
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String newObject(Model model) {
Citizen citizen= citizenDao.getNewObject();
citizen.setIsLoyalToTheParty(true);
model.addAttribute("citizen", citizen);
return "CitizenForm";
}
/*
* Processing the completed forms.
*/
@RequestMapping(value = "/onSubmit", method = RequestMethod.POST)
public String onSubmit(Citizen to citizen, BindingResult result, SessionStatus status, Model model) {
citizenValidator.validate(citizen, result);
if (result.hasErrors()) {
return "СitizenForm";
} else {
citizenDao.save(citizen);
status.setComplete();
return "successView";
}
}
Essence:
@Entity
@Table(name = "ASD_CIT")
public class Citizen implements Serializable {
@Id
private Long id;
private String firstName;
private String secondName;
private boolean IsLoyalToTheParty;
public Citizen(){
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public boolean isIsLoyalToTheParty() {
return IsLoyalToTheParty;
}
public void setIsLoyalToTheParty(boolean IsLoyalToTheParty) {
this.IsLoyalToTheParty = IsLoyalToTheParty;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
And finally, the form:
<form:form commandName="citizen" method="post" action="onSubmit">
<form:hidden path="id" id="id"/>
<form:input path="firstName" id="firstName"/>
<form:input path="secondName" id="secondName"/>
</form:form>
As you can see in the code there is no form field for the property IsLoyalToTheParty — it is established at object creation and editing in the form is not provided.
Question following: in the presented case, the value of the property IsLoyalToTheParty get lost on the way the Controller -> Form -> Controller. If I create a hidden field in the form for this property, it will not be lost. But since real objects are composed of a much greater number of such properties would not want on the form create fields for these properties. How to force to return the shape of the object that was passed to it originally?