Spring framework bind form array property - spring

// my form
public class myForm {
private double[] myField;
public double[] getMyField(){
return myField;
}
public void setMyField(double[] myField){
this.myField = myField;
}
}
// my jsp
...
...
<c:set var="i" value="0"/>
<c:forEach items="${myList}" var="data">
<form:input path="myField[${$i}]"/>
<c:set var="i">${i + 1}</c:set>
</c:forEach>
...
...
After spring render jsp generate this code ;
<input type="text" value="0.0" name="myField0" id="myField0"/>
<input type="text" value="0.0" name="myField1" id="myField1"/>
<input type="text" value="0.0" name="myField2" id="myField2"/>
...
...
Spring cant bind my form on controller , because form names not valid (myField0, myField1..) . If i change names with firebug (as myField[0], myField[1] etc.) initBinder works and i catch my form data on controller. How can i solve this?
Thanks.

Use a Collection in your form instead of an array :
public class myForm {
private Collection<Double> myField;
public Collection<Double> getMyField(){
return myField;
}
public void setMyField(Collection<Double> myField){
this.myField = myField;
}
}

Related

Is greeting view and the result view pointing to the same object?

Here our controller may return one of two views.
In such a case where these 2 method signatures both contained Model Model Map and ModelAttribute, do the views share access to the Model and ModelAttribute loaded by a previous request handle?
#Controller
public class GreetingController {
#GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
#PostMapping("/greeting")
public String greetingSubmit(#ModelAttribute Greeting greeting) {
return "result";
}
}
It does not point the same object.
I am assuming you are using https://spring.io/guides/gs/handling-form-submission/
and its code naming convention is quite confusing.
Please see the following test code.
I changed URL, variable name purposely.
Greeting.java
public class Greeting {
private long id;
private String content;
//... getters and setters
}
Greeting2.java
//created for testing
public class Greeting2 {
private long id;
private String content;
//... getters and setters
}
GreetingController.java
#Controller
public class GreetingController {
#GetMapping("/greeting") // greeting URL and GET request method
public String greetingForm(Model model) {
// th:object="${foo}" in template and thymeleaf
model.addAttribute("foo", new Greeting());
return "greeting_tmpl"; // src/main/resources/templates/greeting_tmpl.html
}
#PostMapping("/greeting_post")
public String greetingSubmit(#ModelAttribute Greeting2 bar) {
//I expected using bar variable in result_tmpl, but it used Greeting2(lowercase) as variable
return "result_tmpl"; // src/main/resources/templates/result_tmpl.html
}
}
src/main/resources/templates/greeting_tmpl.html
...
<body>
<h1>Form</h1>
<form action="#" th:action="#{/greeting_post}" th:object="${foo}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Message: <input type="text" th:field="*{content}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
src/main/resources/templates/result_tmpl.html
...
<body>
<h1>Result</h1>
<p th:text="'id: ' + ${greeting2.id}" /> <!-- this name should be like bar.id not greeting2 -->
<p th:text="'content: ' + ${greeting2.content}" />
Submit another message
</body>
</html>
Simply,
Browser triggers #GetMapping.
Server Parses Greeting model to HTML form values in greeting template and response to the browser.
Submit Form Data using POST method triggers #PostMapping.
#ModelAttribute Greeting2(Can be any model which can parse form values(in this case, id,content) will parse form values to Greeting2 model.
Server Parses Greeting2 model to HTML form values in greeting template and response to the browser.

Error handling with Spring CommandName

when using Spring framework and binding a form on a commandName object to add let's say a person with the following fields.
<form method="POST" action="addPerson.htm" commandName="person">
<input id="firstname" name="firstname"value="${person.firstname}"/>
<br>
<input id="name" name="name" value="${person.name}"/>
<br>
<input id="age" name="age" value="${person.age}"/>
</form>
On the server I've got the following code
#RequestMapping(value="/addPerson", method={RequestMethod.POST})
public String addPerson(#ModelAttribute(value="person") Person p){
service.addPerson(p);
return "redirect:/overview.htm";
}
How do I do error handling with this, so let's say for example the age must be a positive number and firstname can be left empty.
You need to create a new Validator class, implementing Validator interface.
Your validator can be something like this:
public class PersonValidator implements Validator {
public boolean supports(Class<?> clazz) {
return Person.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
Person person=(Person)target;
if ( person.getAge() < 0 ) {
errors.rejectValue("age", "age_positive");
// Or you can use this approach as well to parametrize the error message:
//errors.rejectValue("age", "age_positive", ArrayParametersIfNeeded, "DefaultMessage");
}
}
}
You also need to have a error.properties file to hold the errors messages allowing i18n.
You can have all needed information about validators here: Validators
When you have it, you need to create the initBinder method in the controller:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.addValidators(yourValidator);
}
Then, in the controller method, you can pass this additional parameter: BindingResult result and there you will have the information of the errors if you need it.
Also, you need to add this bit to the form:
<form:errors path="age"/></c:set>
Below your <input id="age" name="age" value="${person.age}"/>
I suggest you to change your <input> elements for the <form:input> tag.

Spring MVC bind multi select with view model on post method

How to bind a multi select to a view model on post method?
This is the view model:
public class AssignEvaluationViewModel {
private String evaluationType;
private String milestone;
private List<AssigneesViewModel> optionsList;
//getters and setters
}
public class AssigneesViewModel {
private int evaluatorId;
private int evaluatedId;
private String evaluatorName;
private String evalueatedName;
}
Controller
#RequestMapping(value="addAssignment", method = RequestMethod.GET)
public String addAssignment(Model model){
// load the list of evaluation type
List<DropDownListItem> items = new ArrayList<DropDownListItem>();
items.add(new DropDownListItem("1", "Peer evaluation"));
items.add(new DropDownListItem("2", "Team member evaluation"));
items.add(new DropDownListItem("3", "Team evaluation"));
model.addAttribute("items", items);
// load the list of milestones
List<DropDownListItem> milestones = new ArrayList<DropDownListItem>();
List<MilestoneDTO> dtos = milestoneService.getAll();
for (MilestoneDTO m : dtos) {
milestones.add(new DropDownListItem(String.valueOf(m.getId()), m
.getMilestoneName()));
}
model.addAttribute("milestones", milestones);
model.addAttribute("addAssignment", new AssignEvaluationViewModel());
return "addAssignment";
}
#RequestMapping(value="addAssignment", method = RequestMethod.POST)
public String addAssignmentPOST(#ModelAttribute("addAssignment") AssignEvaluationViewModel viewModel){
//save the assignment
return "redirect:assignEvaluationForms";
}
The problem is in the jsp.
<form:form commandName="" modelAttribute="addAssignment" id="addAssignment">
//..................
<div class="selectAssignees">
<p>Assignees:</p>
<form:select multiple="multiple" class="assigneesOptions" path="optionsList" id="assignees">
</form:select>
</div>
//..............
</form:form>
How do i bind the options added by the user in the select with optionsList from the AssignEvaluationViewModel?
If you want to show options in Spring you can use form:options
<form:form commandName="" modelAttribute="addAssignment" id="addAssignment">
<div class="selectAssignees">
<p>Assignees:</p>
<form:select multiple="multiple" class="assigneesOptions" path="optionsList" id="assignees">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${optionsList}" />
</form:select>
</div>
</form:form>

Redirect on Spring Tiles Causing Parameters to be Appended to the URL

I am using Spring 3 and Tiles 3. Below is just a simplified example I made. I have a test controller where I list all the SimpleEntity objects. And there is an input field on the JSP to add a new entity via a POST. Here is the controller.
#Controller
#RequestMapping(value="/admin/test")
public class TestAdminController {
private String TEST_PAGE = "admin/test";
#Autowired
private SimpleEntityRepository simpleEntityRepository;
#ModelAttribute("pageName")
public String pageName() {
return "Test Administration Page";
}
#ModelAttribute("simpleEntities")
public List<SimpleEntity> simpleEntities() {
return simpleEntityRepository.getAll();
}
#RequestMapping(method=RequestMethod.GET)
public String loadPage() {
return TEST_PAGE;
}
#RequestMapping(method=RequestMethod.POST)
public String addEntity(#RequestParam String name) {
SimpleEntity simpleEntity = new SimpleEntity();
simpleEntity.setName(name);
simpleEntityRepository.save(simpleEntity);
return "redirect:/" + TEST_PAGE;
}
}
Everything works fine. However, when I submit the form, the URL adds the pageName parameter, so it goes from /admin/test to /admin/test?pageName=Test+Administration+Page. Is there anyway to prevent this from happening when the page reloads?
UPDATE
Here is the JSP form.
<form:form action="/admin/test" method="POST">
<input type="text" name="name" />
<input type="submit" name="Save" />
</form:form>

#NumberFormat Annotation not working

Trying to show the currency symbol in JSP but I don't see it. Did my research and I just don`t know what more should I add to get it working. This is what I have.
<mvc:annotation-driven />
Controller
#NumberFormat(style = Style.CURRENCY)
private Double value = 50.00;
#ModelAttribute("value")
#NumberFormat(style = Style.CURRENCY)
public Double getValue() {
return value;
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView loadForm(#ModelAttribute("user") User user) {
ModelAndView instance
modelAndView.addObject("value", 100.00);
return modelAndView;
}
JSP
<spring:bind path="value">
<input type="text" name="${value}" value="${value}"/>
</spring:bind>
<spring:bind path="value">
${value}
</spring:bind>
Output
<input type="text" name="value" value="100.0"/>
100.0
Try using the string literal value for the name attribute instead of resolving it with EL
<spring:bind path="value">
<input type="text" name="value" value="${value}"/>
</spring:bind>
Also, move the field value into a new object. Currently I do not believe the code is using the field in the controller or the getter in the controller.
public class MyForm(){
#NumberFormat(style = Style.CURRENCY)
private Double value = 50.00;
#ModelAttribute("value")
#NumberFormat(style = Style.CURRENCY)
public Double getValue() {
return value;
}
}
Then add the object to the model in the controller:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView loadForm(#ModelAttribute("user") User user) {
ModelAndView instance
modelAndView.addObject("myForm", new MyForm());
return modelAndView;
}
Then access via the jsp:
<spring:bind path="myForm.value">
<input type="text" name="${status.expression}" value="${status.value}"/>
</spring:bind>
<spring:bind path="myForm.value">
${status.value}
</spring:bind>
The major issue at the moment with the code is that it is not using the field/accessor, it is simply placing a value in the model, which does not use any of the annotated fields/methods.
References:
http://www.captaindebug.com/2011/08/using-spring-3-numberformat-annotation.html#.UOAO_3fghvA
How is the Spring MVC spring:bind tag working and what are the meanings of status.expression and status.value?

Resources