有什么办法可以在modelAttribute中将字节数组转换为String?

时间:2020-05-30 12:13:53

标签: arrays spring-boot spring-mvc modelattribute

我有一个名为“ Post”的模型类,该类具有作为字节数组的属性“ postContent”。

public class Post{
byte[] postContnet;

//getters
//setters
...
}

因此,我正在使用spring boot和spring form标签来使用modelAttribute获取用户的输入。我使用字节数组的原因是我使用Ckeditor来获取所见即所得的内容。

    <form:form ...... modelAttribute="post">
   ...
    <form:textarea path="postContect" id="editor1">
....
    </form:form>

在将帖子插入数据库时​​,我没有进行任何转换,而是将其插入到MySQL数据库中,其中postContent列为Blob类型。但是,当出于编辑目的而取回内容时,我得到的是字节数组,而应该是字符串。在控制器中,我正在获取数据并将其发送到JSP,如下所示:

....
Post post = postService.findByPostId(postId);
        if (post != null) {
            mv.addObject("title", "Edit Post");
            mv.addObject("post", post);
 ...

因此,当我在JSP中使用JSTL时,它将postContect打印为数组。我可以在将String转换为字节数组(反之亦然)时获得许多引用,但是在这里,因为我使用的是spring form和modelAttribute,所以我不确定应该在哪里编辑。我该如何找回介于它们之间的String?

谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了答案,对我有用。我在这里添加评论,是因为有类似问题的人会有所想法。

  1. 我为字符串到字节数组创建了Spring转换器

    @Component 公共类StringBase64ToByteArray实现Converter {

    @Override
    public byte[] convert(String source) {
        byte[] byteSource = null;
        System.out.println("StringBase64ToByteArray is called");
        try {
            byteSource = Base64.getEncoder().encode(source.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return byteSource;
    }
    

    }

  2. 然后我创建了另一个转换器,将字节数组转换为字符串

    @Component 公共类ByteArrayToStringBase64实现Converter {

    @Override
    public String convert(byte[] source) {
        byte[] decodedString = Base64.getDecoder().decode(source);
        return new String(decodedString);
    }
    

    }

  3. 我已经将两个转换器注册为Spring Boot配置 @组态 公共类WebMvcConfig实现WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringBase64ToByteArray());
        registry.addConverter(new ByteArrayToStringBase64());
    }   
    

    }