关于Mvc
框架,我还是喜欢使用ActFramework,它基本上可以不用写注解,而SpringMvc
就需要写很多注解,我觉得很多东西都是可以自动去判断的,而不需要写一个注解去强行指定。
RequestBody
默认只支持Content-Type
为Application/json
,当Content-Type
为其他时会抛出415
异常(不支持的Content-Type
).
@RequestBody
是由HttpMessageConverter
来根据请求体转换为对象的,Application/json
默认是由MappingJackson2HttpMessageConverter
来转换的,所以我们可以自定义一个HttpMessageConverter
来转换application/x-www-form-urlencoded
。
代码:
@Service
class MappingJackson2HttpMessageFormConverter(
objectMapper: ObjectMapper
): AbstractJackson2HttpMessageConverter(objectMapper, MediaType.APPLICATION_FORM_URLENCODED) {
override fun read(type: Type, contextClass: Class<*>?, inputMessage: HttpInputMessage): Any {
val inputStream = StreamUtils.nonClosing(inputMessage.body);
val body = String(inputStream.readAllBytes())
val objectNode = objectMapper.createObjectNode()
val split = body.split("&")
for (single in split) {
val keyValue = single.split("=")
if (keyValue.size == 2) {
val prefix = URLDecoder.decode(keyValue[0], Charset.defaultCharset())
val suffix = URLDecoder.decode(keyValue[1], Charset.defaultCharset())
objectNode.put(prefix, suffix)
}
}
val javaType = getJavaType(type, contextClass);
return objectMapper.convertValue(objectNode, javaType)
}
override fun canWrite(clazz: Class<*>, mediaType: MediaType?): Boolean {
return super.canWrite(clazz, mediaType ?: return false)
}
}