我有一个 Spring-MVC 应用程序。在控制器中,我一直使用 @ModelAttribute 将表单详细信息映射到 POJO。 现在,我要求表单也发送一个文件。我已经在 JSP 文件和 POJO 文件中进行了所需的更改。但是,现在这些值没有被映射。
唯一的问题是定义默认的多部分解析器是不可行的。这是因为之前在 Struts 中、现在迁移到 Spring 中的代码在业务逻辑本身中解析请求。
我能做什么?
控制器:
@RequestMapping(value = "/getUserDetails", method = RequestMethod.POST, consumes = "multipart/form-data")
public String getUserDetails(@ModelAttribute("user") User user) {
System.out.println(user);
return "display-user";
}
JSP 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo Form</title>
</head>
<body>
<form action="getUserDetails" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td>Name: </td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td>Age: </td>
<td><input type="number" name="age" step="1"></td>
</tr>
<tr>
<td>Marks: </td>
<td><input type="number" name="marks"></td>
</tr>
<tr>
<td>DOB: </td>
<td><input type="date" name="dob"></td>
</tr>
<tr>
<td>File: </td>
<td><input type="file" name="file"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit">
<input type="reset">
</td>
</tr>
</table>
</form>
</body>
</html>
用户POJO:
package com.habib.model;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
public class User {
private String name;
private String lastName;
private int age;
private double marks;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date dob;
MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getMarks() {
return marks;
}
public void setMarks(double marks) {
this.marks = marks;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
", marks=" + marks +
", date=" + dob.toLocaleString() +
'}';
}
}
您可以定义类级别 bean 来配置多部分处理。
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(10485760); // 10 MB
multipartResolver.setDefaultEncoding("utf-8");
return multipartResolver;
}
@RequestParam("file") MultipartFile file