其他分享
首页 > 其他分享> > 自定义返回数据转换器MessageConverter(请求和响应之间进行转换的策略接口)

自定义返回数据转换器MessageConverter(请求和响应之间进行转换的策略接口)

作者:互联网

配置类

import com.example.studywork1.pojo.User;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class MyMessageConverter implements HttpMessageConverter<User> {

    // 是否能读
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    // 是否能写
    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        // 如果是user类型返回true 可以写
        return clazz.isAssignableFrom(User.class);
    }

    // 自定义返回此转换器支持的媒体类型  自定义:application/xxxx
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/xxxx");
    }

    // 上面是否能读为false 这个方法不需要操作
    @Override
    public User read(Class<? extends User> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    // 重新写的方法
    @Override
    public void write(User user, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        // 自定义协议数据的写出
        String data = "自定义写的结果------姓名:" + user.getName()+"年龄:"+user.getAge();
        OutputStream body = outputMessage.getBody();
        // 放入body中 输出出去
        body.write(data.getBytes(StandardCharsets.UTF_8));
    }
}
@Component
public class MyConfig {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {

            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                converters.add(new MyMessageConverter());
            }
        };
    }
}
@Controller
public class MyController {
    @ResponseBody
    @GetMapping("/getUser")
    public User getUser(){
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        return user;
    }
}

输出结果

 

标签:return,自定义,MessageConverter,springframework,user,import,转换器,public,User
来源: https://www.cnblogs.com/dabo-tian/p/16520599.html