Unable to get form data in controller in spring mvc

I am new to spring mvc framework, and I ran into the problem of getting values ​​from a view in a controller. Below is the code.

Here is the jsp:

<form:form action="envDetails" method="POST" commandName="enviromentForm">
<c:forEach items="${enviromentForm.environments}" varStatus="i" var="env">
        Name of Environment<c:out value="${(i.index)+1}"/>:
       <form:input path="environments[${i.index}].name" type="text"/>
       <br>
       Path of Environment<c:out value="${(i.index)+1}"/>  :
       <form:input path="environments[${i.index}].path" type="text"/>
       <br><br>
</c:forEach>
<input class="submitStyle" type="submit" value="SUBMIT" />
</form:form>

This is my controller:

@RequestMapping(value="envDetails",method=RequestMethod.GET)
public ModelAndView setBackingForm(HttpServletRequest request) {
    EnviromentForm envf=new EnviromentForm();
    envf.setProjectName("Test");
    for(int i=0;i<2;i++) {
        envf.add(new Enviroment());
    }
    return new ModelAndView("envDetails","enviromentForm",envf);
}

@RequestMapping(value = "envDetails", method = RequestMethod.POST)
public ModelAndView viewFolderInput(
        @ModelAttribute("enviromentForm") EnviromentForm enviromentForm,BindingResult binding,WebRequest request, SessionStatus status) {

    ***//here I am not receiving the values in enviromentForm***
}

This is the EnviromentForm class:

public class EnviromentForm {

private String projectName;
private List<Enviroment> environments;

public EnviromentForm() {
    environments = new ArrayList<>();
}

public EnviromentForm(String projectName, List<Enviroment> environments) {
    this.projectName = projectName;
    this.environments = new ArrayList<>();
    this.environments.addAll(environments);
}

//getter setter

public void add(Enviroment env) {
    this.environments.add(env);
}

}

and this is the Enviroment class:

public class Enviroment {
private String name;
private String path;

//getter setter

}

Any help is greatly appreciated.

+3
source share
2 answers

The main problem is that Spring MVC 3.0.1 displays the tag <form:input>in HTML as:

<input id="environments0.path" name="environments0.path" value="" type="text">

Note that there are nameno brackets ( []) in the attribute , which makes it compatible with the HTML specification, but breaks the data binding. There are two ways to solve this problem: updating Spring or using a regular tag input. I would recommend updating Spring.

Spring

- Spring. , 3.2.5.RELEASE :

enter image description here

3.0.1.RELEASE, :

enter image description here

HTML

HTML input . Spring 3.0.1 path ( name).

<input name="environments[${i.index}].name" type="text"/>
+1

@Controller(value = "/") @RequestMapping(value="/") EnvController.

@Controller , Spring bean. @Controller

, add(). , , getter environments

:

environmentForm.getEnvironments().add(env);
0

All Articles