【问题标题】:Exception org.springframework.validation.BeanPropertyBindingResult异常 org.springframework.validation.BeanPropertyBindingResult
【发布时间】:2013-02-25 16:36:56
【问题描述】:

我正在尝试使用 apache commons 上传图片,但在与我的实体绑定时出现异常。

表单对象

<sf:form action="${contextPath}client/saveClient" modelAttribute="client" method="POST"
                 enctype="multipart/form-data"> 
            <label>Add Logo</label><input type="file"  name='logo' /><br/>
        </sf:form>

控制器

 @RequestMapping("/saveClient")
    public ModelAndView addClient(@RequestParam("logo") MultipartFile file, HttpSession request,
            @Valid Client client, BindingResult result, Model model) throws IOException {

        ModelAndView mvc = new ModelAndView();
        if (result.hasErrors()) {
            mvc.addObject("client", client);
            mvc.setViewName(MANAGECLIENT_PREFIX + "addclient");
            return mvc;
        } else {
            clientService.uploadImage(file, request);
            clientRepository.add(client);
            model.addAttribute("client", client);
            mvc.setViewName(MANAGECLIENT_PREFIX + "saveclient");
            return mvc;
        }
    }

服务

public void uploadImage(MultipartFile file, HttpSession request) throws IOException {
    logger.info("Enter upload client logo");
    Utilities utilities = new Utilities();
    if (!file.isEmpty()) {
        String fileName = (utilities.getUniqueId() + file.getOriginalFilename());
        System.out.println("Image name: {" + fileName + "}");
        String contextPath = request.getServletContext().getRealPath("/");
        String filePath = contextPath + "\\WEB-INF\\clientlogo\\" + fileName;
        String validFileFormat = utilities.validFileFormat(fileName);
        if (!validFileFormat.isEmpty()) {
            BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
            File destination = new File(filePath);
            ImageIO.write(src, validFileFormat, destination);
            client.setLogo(fileName);
        }
    }
}

实体

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

异常

Field error in object 'client' on field 'logo': rejected value [org.springframework.web.multipart.commons.CommonsMultipa
rtFile@58d51629]; codes [typeMismatch.client.logo,typeMismatch.logo,typeMismatch.java.lang.String,typeMismatch]; argumen
ts [org.springframework.context.support.DefaultMessageSourceResolvable: codes [client.logo,logo]; arguments []; default
message [logo]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.commons.Co
mmonsMultipartFile' to required type 'java.lang.String' for property 'logo'; nested exception is java.lang.IllegalStateE
xception: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type
 [java.lang.String] for property 'logo': no matching editors or conversion strategy found]}]

我正在尝试将图像名称存储在数据库中,并将图像存储在应用程序目录中。我应该如何解决这种类型转换。

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    异常说

    无法转换类型的值 [org.springframework.web.multipart.commons.CommonsMultipartFile] 到 属性“logo”所需的类型 [java.lang.String]:无匹配 找到编辑器或转换策略]}]

    因为你在MultipartFile parameter上定义了@RequestParam("logo")

    【讨论】:

      【解决方案2】:

      这只是一个绑定错误 - 您的对象“客户端”具有不同类型的“徽标”属性。您可以忽略该特定错误。

      用途:

      if (result.hasErrors() && (result.getErrorCount()>1 || !result.hasFieldError("logo")) {
       ....
      } 
      

      含义:只有在出现超过 1 个错误('logo' 字段总是有错误)或者你遇到的单个错误不是 'logo' 错误时,您才应该对错误做出反应。

      【讨论】:

        【解决方案3】:

        第 1 步:在表单标签中添加 enctype="multipart/form-data" 属性。

        步骤2:注册一个MultipartResolver bean,并在配置文件/类中返回CommonsMultipartResolver,并确保bean名称必须为“multipartResolver”,默认情况下Spring使用方法名称作为bean名称。

        第 3 步:创建数据库连接对象并将其注入 DAO 类。

        第4步:使用注入的数据库连接使用JdbcTemplate查询数据库。

        第 5 步:最后创建一个处理用户请求的控制器类。

         @Configuration
            @EnableWebMvc
            @ComponentScan(basePackages = { "org.websparrow.controller", "org.websparrow.dao" })
            public class WebMvcConfig {
        
                @Bean
                public InternalResourceViewResolver viewResolver() {
        
                    InternalResourceViewResolver vr = new InternalResourceViewResolver();
                    vr.setPrefix("/");
                    vr.setSuffix(".jsp");
        
                    return vr;
                }
        
                @Bean
                public MultipartResolver multipartResolver() {
                    return new CommonsMultipartResolver();
                }
        
                @Bean
                public DriverManagerDataSource getDataSource() {
        
                    DriverManagerDataSource ds = new DriverManagerDataSource();
                    ds.setDriverClassName("com.mysql.jdbc.Driver");
                    ds.setUrl("jdbc:mysql://localhost:3306/yourdatabase");
                    ds.setUsername("root");
                    ds.setPassword("");
        
                    return ds;
                }
        
                @Bean
                public ImageDao getConnectionObject() {
                    return new ImageDao(getDataSource());
                }
            }
            public class ImageDao {
        
                private JdbcTemplate jdbcTemplate;
        
                public ImageDao(DataSource dataSource) {
                    jdbcTemplate = new JdbcTemplate(dataSource);
                }
        
                public int inserRecords(String name, Integer age, MultipartFile photo) throws IOException {
        
                    byte[] photoBytes = photo.getBytes();
        
                    String sql = "INSERT INTO STUDENT(NAME,AGE,PHOTO) VALUES (?,?,?)";
        
                    return jdbcTemplate.update(sql, new Object[] { name, age, photoBytes });
                }
            }
        
            @Controller
            public class ImageController {
        
                @Autowired
                ImageDao imageDao;
        
                @RequestMapping(value = "/InsertImage", method = RequestMethod.POST)
                public ModelAndView save(@RequestParam("name") String name, @RequestParam("age") Integer age,
                        @RequestParam("photo") MultipartFile photo) {
        
                    try {
                        imageDao.inserRecords(name, age, photo);
        
                        return new ModelAndView("index", "msg", "Records succesfully inserted into database.");
        
                    } catch (Exception e) {
                        return new ModelAndView("index", "msg", "Error: " + e.getMessage());
                    }
                }
            }
        //Database
            CREATE TABLE `student` (
              `id` int(5) NOT NULL AUTO_INCREMENT,
              `name` varchar(30) DEFAULT NULL,
              `age` int(3) DEFAULT NULL,
              `photo` mediumblob,
              PRIMARY KEY (`id`)
            );**strong text**
        //html form
        <form action="InsertImage" method="post" enctype="multipart/form-data">
        
        <pre>
        
            Name: <input type="text" name="name">
        
            Age: <input type="number" name="age">
        
            Photo: <input type="file" name="photo">
        
            <input type="submit" value="Submit">
        
        </pre>
        
        </form>
        

        【讨论】:

        • @RequestParam("logo") MultipartFile 文件将其更改为 @RequestParam("file") MultipartFile 文件并试一试。如果没有解决,您可以按照答案中描述的方式进行操作。 @Talha Bin Shakir
        猜你喜欢
        • 2014-09-08
        • 1970-01-01
        • 2020-09-11
        • 2019-03-18
        • 1970-01-01
        • 2016-09-11
        • 2021-12-05
        • 2012-06-17
        • 1970-01-01
        相关资源
        最近更新 更多