Spring tag <form:input>
can generate <input>
tag with id and name attributes. I think this feature is useful and I want to use this when using non form object.
Please take a look at codes below.
"dto" object is added to "model" object as well as "form" then I want to generate id attribute automatically. However, <form:input>
tag seems to be able to use for binding form object. Do I have to make a custom tag in order to realize the similar feature? Any help will be appreciated?
[Controller]
@RequestMapping(method = RequestMethod.GET)
public String show(Model model, HttpServletRequest request) {
SampleForm form = new SampleForm();
form.setName("Name of Form Object");
SampleDto dto = new SampleDto();
dto.setName("Name of Dto Object");
model.addAttribute("form", form);
model.addAttribute("dto", dto);
return "sample/input";
}
[JSP]
<body>
<form:form modelAttribute="form" method="post">
<%-- Generate with id attribute like <input id="name" name="name" type="text" value="Name of Form Object"/> --%>
<form:input path="name" />
<%-- I tried below but an error occured--%>
<%-- <form:input path="${dto.name}" /> --%>
<%-- Just a String display like "Name of Dto Object" --%>
${dto.name}
<input type="submit" name="register" value="register" />
</form:form>
</body>
[Form]
public class SampleForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
[Dto]
public class SampleDto {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
A form can only have one backing object. In your example the backing object is an instance of SampleForm. You could add a reference to a SampleDto instance in your SampleForm class:
public class SampleForm {
private String name;
private SampleDto dto;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SampleDto getDto() {
return dto;
}
public void setDto(SampleDto dto) {
this.dto = dto;
}
}
Then you could do this in your JSP:
<form:input path="dto.name"/>