I have a Spring-MVC application. In a controller, I have been mapping the forms details to a POJO using @ModelAttribute.
Now, I require that the form sends a file as well. I have made the required changes in the JSP file and POJO files. But, now the values are not getting mapped.
The only catch is that defining a default multipart resolver is not feasible. This is because the code which was previously in Struts and now migrated to Spring parses the request in the business logic itself.
What can I do?
Controller:
@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 File:
<!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>
User 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() +
'}';
}
}