本文主要是介绍spring-boot使用自定义HttpMessageConverter将application/x-www-form-urlencoded请求数据转为对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.定义converter
public class CustomerMessageConverter extends AbstractHttpMessageConverter<T> {private static final FormHttpMessageConverter formHttpMessageConverter=new FormHttpMessageConverter();private static final ObjectMapper mapper=new ObjectMapper();@Overrideprotected boolean supports(Class<?> aClass) {return T.class==aClass;}@Overrideprotected T readInternal(Class<? extends T> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {Map<String,String> map=formHttpMessageConverter.read(null,httpInputMessage).toSingleValueMap();return mapper.convertValue(map,T.class);}@Overrideprotected void writeInternal(T t, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {}
}
2.MvcConfiguer中添加自定义converter
@Configuration
public class MvcConfigurer implements WebMvcConfigurer {@Beanpublic CustomerMessageConverter customerMessageConverter() {CustomerMessageConverter converter=new CustomerMessageConverter();converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));return converter;}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(customerMessageConverter());}
}
3.编写实体类
@Data
public class Student {String name;int age;String phone;String address;String reqJson;
}
4.编写controller
@RestController
@RequestMapping(value = "/test")
public class TestController {private Logger logger= LoggerFactory.getLogger(getClass());@PostMapping(consumes = {"application/x-www-form-urlencoded;charset=UTF-8"})public WebResponseResult test(@ModelAttribute Student student) {logger.info("---"+student.getName()+","+student.getAge()+","+student.getPhone()+","+student.getAddress());return WebResponseResult.success(student);}
}
5.使用postman测试
这篇关于spring-boot使用自定义HttpMessageConverter将application/x-www-form-urlencoded请求数据转为对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!