简体   繁体   中英

Spring mvc handling differences in types between form and model

I have this form

<form:form action="saveCustomer" modelAttribute="customer" enctype="multipart/form-data" method="POST">
    <!-- need to associate this data with customer id -->
    <form:hidden path="id" />

    <table>
        <tbody>
            <tr>
                <td><label>First name:</label></td>
                <td><form:input path="firstName" /></td>
            </tr>

            <tr>
                <td><label>Last name:</label></td>
                <td><form:input path="lastName" /></td>
            </tr>

            <tr>
                <td><label>Email:</label></td>
                <td><form:input path="email" /></td>
            </tr>
            <tr>
            <td><label>Profile Image:</label></td>
                <td>
                <form:input type="file" path="file" id="file" class="form-control input-sm"/>
                </td>
            </tr>

            <tr>
                <td><label></label></td>
                <td><input type="submit" value="Save" class="save" /></td>
            </tr>

        </tbody>
    </table>    
</form:form>

and this model

@Entity
@Table(name="customer")
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="email")
    private String email;

    @NotEmpty
    @Column(name="file")
    private String file;
}

In my model, I have decided not to define the file field as MultipartFile and instead I went with String .

I did that to enable me just grab the uploaded files file name and leave spring mvc to upload the file. That works but when I introduce error checking I get this error:

org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'customer' on field 'file': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@2a8400bb]; codes [typeMismatch.customer.file,typeMismatch.file,typeMismatch.java.lang.String,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [customer.file,file]; arguments []; default message [file]]; default message [Failed to convert property value of type [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile] to required type [java.lang.String] for property 'file'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile] to required type [java.lang.String] for property 'file': no matching editors or conversion strategy found]

My controller:

@RequestMapping(value = "/saveCustomer", method = RequestMethod.POST)
public String saveCustomer(@Valid FileBucket fileBucket,
        ModelMap model, @ModelAttribute("customer") Customer theCustomer,BindingResult result) throws IOException {

    if (result.hasErrors()) {
        System.out.println("validation errors");
        return "customer-form";
    } else {
        System.out.println("Fetching file");
        MultipartFile multipartFile = fileBucket.getFile();

        // Now do something with file...
        FileCopyUtils.copy(fileBucket.getFile().getBytes(), new File( UPLOAD_LOCATION + fileBucket.getFile().getOriginalFilename()));
        String fileName = multipartFile.getOriginalFilename();
        model.addAttribute("fileName", fileName);
        theCustomer.setFile(fileName);
        customerService.saveCustomer(theCustomer);  
        return "redirect:/customer/list";
    }
}

How can I handle this error?

In your error part say about this only

typeMismatch.customer.file,typeMismatch.file,typeMismatch.java.lang.String,typeMismatch

but in entity class file is a string

 <form:form action="saveCustomer" modelAttribute="customer" enctype="multipart/form-data" method="POST">

In your form

<form:input type="file" path="file" id="file" class="form-control input-sm"/> 

but, here your modelAttribute is customer front end its and file input and backend it's a String so that your having problem

private String file is incorrect param because it's a multipart data so you should use MultipartFile in your entity class

 @Entity
 @Table(name="customer")
 public class Customer {

  ... . .  . . .. 
  private MultipartFile file;

  //getters setters

 }

I created another field called path and made file transient

@Entity
@Table(name="customer")
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="email")
    private String email;

    @NotEmpty
    @Column(name="path")
    private String path;

    @Transient
    private MultipartFile file;

and that worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM