提问者:小点点

当提交的表单具有属性enctype=“multipart/form-data”时,如何在控制器中获取表单数据?


当jsp中的表单包含属性enctype=“multipart/formdata”时,我在控制器中获取表单数据时遇到了一些问题。该属性是必需的,因为我正在上载文件。我简化了代码以使其更易于理解,但假设我有以下内容。

我的型号:

public class EmployeeUpdateForm {
    private String name;
    private ContactInfo info;
    //standard getters and setters
}
public class ContactInfo {
    private String streetName;
    private MultipartFile image;
    //standard getters and setters
}

我的控制器是

@Controller
public class EmployeeController {

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public ModelAndView showForm() {
        //assume this sends you to updateEmployee.jsp
 
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submit(@ModelAttribute("EmployeeUpdateForm")EmployeeUpdateForm form ) {
        //here I expect form.getInfo().getStreetName() and form.getInfo().getImage() to return something but they are both null values.
    }
}

更新员工.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
    <head>
    </head>
    <body>
        <h3>Update Employee Details</h3>
        <form:form action="submit" method="post" enctype="multipart/form-data" id="EmployeeUpdateForm" modelAttribute="EmployeeUpdateForm">
             <div>
                 Street Name: <form:input path="info.streetName" />
             </div>
             <div>
                 New Image: <form:input type="file" path="info.image"/>
             </div>
        </form:form>
    </body>
</html>

当我提交表单并检查form.getInfo()的值时。getStreetName()和form.getInfo()。我的控制器中submit()内的getImage(),两个值都是null。

但是,如果我从 jsp 中的表单中删除方法=“post” enctype=“multipart/form-data” 并删除

当jsp中的表单具有属性method = " post " enctype = " multipart/form-data "时,如何在控制器中获取表单数据??


共1个答案

匿名用户

缺少一个解析程序。加

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>

解决了这个问题。