深入浅出Spring MVC (2)

实现RequestBodyAdvice 接口即可。比如我需要处理requestbody中的内容,将emoji输入转换掉

@RestControllerAdvice public class EmojiReplaceAdvice implements RequestBodyAdvice { @Override public boolean supports(final MethodParameter methodParameter, final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) { return methodParameter.hasParameterAnnotation(EmojiReplace.class); } @Override public Object handleEmptyBody(final Object body, final HttpInputMessage inputMessage, final MethodParameter parameter, final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) { return body; } @Override public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, final MethodParameter parameter, final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) throws IOException { return new HttpInputMessage() { @Override public InputStream getBody() throws IOException { final String content = IOUtils.toString(inputMessage.getBody()); final String emojiUnicodeToAlias = StringUtil.parseEmojiUnicodeToAlias(content); return new ByteArrayInputStream( emojiUnicodeToAlias.getBytes(StandardCharsets.UTF_8)); } @Override public HttpHeaders getHeaders() { return inputMessage.getHeaders(); } }; } @Override public Object afterBodyRead(final Object body, final HttpInputMessage inputMessage, final MethodParameter parameter, final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) { return body; } } 总结

这篇文章主要是系统的概括了SpringMVC的工作原理和各种扩展机制,属于高度概括,细节不足。具体的每个扩展点的实现、坑、应用场景需要在之后的文章继续阐述。

参考

https://fredal.xin/develop-with-transparent-rpc

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyyzpz.html