java 如何使用@ModelAttribute 将列表绑定到 JSP 表单中的控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6604301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:35:12  来源:igfitidea点击:

How to bind a List using @ModelAttribute to controller from a JSP form

javajspspring-mvc

提问by saran

I am trying to get a list of selected candidates to my controller using @modelAttribute with their respective id and blurb. I am able to bring one Candidate correctly but i don't know how to bring a list of candidates thru... I tried to add List<> as i have shown below, but i get

我正在尝试使用 @modelAttribute 及其各自的 id 和 blurb 将选定候选者的列表添加到我的控制器中。我能够正确地带一名候选人,但我不知道如何通过...带上候选人名单...我尝试添加 List<>,如下所示,但我得到了

ERROR - SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/panel-requests] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.List]: Specified class is an interface] with root cause org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.List]: Specified class is an interface

错误 - 严重:servlet [dispatcher] 的 Servlet.service() 在路径 [/panel-requests] 的上下文中抛出异常 [请求处理失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 bean 类 [java.util.List]:指定的类是一个接口],其根本原因是 org.springframework.beans.BeanInstantiationException:无法实例化 bean 类 [java.util .List]:指定的类是一个接口

JSP -

JSP -

<form:form modelAttribute="candidateAddAttribute" 
  action="/panel-requests/requests/${panelRequestForId.id}/empl" method="post">
<c:forEach items="${candidates}" var="candidates">
    <select name="employee" id="employee" disabled="disabled">
        <option value="default" selected="selected">${candidates.candidateName}</option>
    </select>
    <textarea rows="3" cols="40" id="candidateBlurb" name="candidateBlurb" 
      disabled="disabled">${candidates.candidateBlurb}</textarea>

    <textarea rows="2" cols="20" id="candidateCV" name="candidateCV"                                
      disabled="disabled">${candidates.candidateCV}</textarea>
</c:forEach>
<div id="candidateDiv" id="candidateDiv">
    <select name="employee" id="employee">
        <option value="default" selected="selected">Select Employee</option>
        <c:forEach items="${employees}" var="employee">
            <option value="${employee.id}" id="${employee.id}">
                ${employee.employeeName}- ${employee.employeeCV}<
            /option>
        </c:forEach>
    </select>   
    <textarea rows="3" cols="40" id="candidateBlurb"                
      name="candidateBlurb">BLURB</textarea>
    <div id="employeeCv"></div>
    <input type="submit" value="Add Candidate" />
</div>
</form:form>

The above form at first displays list of employee and when user selects employee, enters blurb and hits add candidate button, i take data to controller.

上面的表单首先显示员工列表,当用户选择员工,输入简介并点击添加候选按钮时,我将数据带到控制器。

Controller:

控制器:

@RequestMapping(value = "{id}/empl", method = RequestMethod.POST)
public String getEmployeeDetails(
    @ModelAttribute("candidateAddAttribute") @Valid List<Candidate> candidates,
    BindingResult result, @PathVariable("id") int requestId, Model model) {

        //implementation goes here
}

How do I implement List in this case? Thanks in advance.

在这种情况下如何实现 List ?提前致谢。

EDITED PARTI tried sending 2 candidate's details, firebug sends it correctly like - Parameters candidateBlurb BLURB sar candidateBlurb BLURB dann employee 1 employee 2

编辑部分我尝试发送 2 个候选人的详细信息,firebug 正确发送它,如 - 参数CandidateBlurb BLURB sarCandidateBlurb BLURB dann员工1员工2

so it can be a problem in initBinder that i ma using, binder.registerCustomEditor(Employee.class, new PropertyEditorSupport() { public String getAsText() { return Long.toString(((Employee) getValue()).getId()); }

所以它可能是我使用的 initBinder 中的一个问题, binder.registerCustomEditor(Employee.class, new PropertyEditorSupport() { public String getAsText() { return Long.toString(((Employee) getValue()).getId()) ; }

                public void setAsText(final String text) {
                    Employee employee = Employee.findById(Integer
                            .parseInt(text));
                    setValue(employee);
                }
            });

which only takes 1 employee detail at a time. Is that a problem here???

一次只需要 1 个员工详细信息。这里有问题吗???

回答by matt b

Create a POJO class which contains the List as a property, such as

创建一个包含 List 作为属性的 POJO 类,例如

public class EmployeeForm {
     private List<Candidate> candidates;
     public List<Candidate> getCandidates() { ... }
     public void setCandidates(List<Candidates>) { ... }
}

and use this in your @RequestMapping method's signature rather than a List<Candidate>directly.

并在您的 @RequestMapping 方法的签名中使用它而不是List<Candidate>直接使用它。

The error message you get is Spring complaining that it doesn't know how to instantiate a List interface, in order for Spring to bind the request parameters in the form to it. You want to provide a simple form/command class to data-bind the form parameters to, Spring knows how to handle a list from there.

您得到的错误消息是 Spring 抱怨它不知道如何实例化 List 接口,以便 Spring 将表单中的请求参数绑定到它。您想提供一个简单的表单/命令类来将表单参数数据绑定到,Spring 知道如何从那里处理列表。

回答by wangjin

you can try this :

你可以试试这个:

List<Candidate> candidates = ListUtils.lazyList(new ArrayList<Candidate>(),FactoryUtils.instantiateFactory(Candidate.class));

回答by Trevor

I've run into this same issue, half of the fields are binding correctly and half aren't. I noticed that the half that are not binding correctly (thus giving me NULL in the controller) were wrapped in a DIV.

我遇到了同样的问题,一半的字段绑定正确,另一半没有。我注意到没有正确绑定的一半(因此在控制器中给我 NULL)被包裹在一个 DIV 中。

When I moved these fields outside the DIV, bingo, they were bound properly in the controller.

当我将这些字段移到 DIV 之外时,宾果游戏,它们在控制器中正确绑定。

I see that you have some fields wrapped in a DIV too, I'd recommend moving them out and seeing if they become visible to your controller.

我看到您也有一些字段包含在 DIV 中,我建议将它们移出并查看它们是否对您的控制器可见。