简体   繁体   English

如何使用Spring MVC Jackson拦截HttpServletRequest

[英]How to intercept HttpServletRequest with Spring MVC Jackson

I'm using Spring/Jackson to auto convert json to POJOs. 我正在使用Spring / Jackson将json自动转换为POJO。 All is working fine, except when I'm doing my header authentication (using a filter). 一切工作正常,除非我正在执行标头身份验证(使用过滤器)。 I've been using request.getContentLength() to get the length of the json string. 我一直在使用request.getContentLength()来获取json字符串的长度。

This worked fine, until the json contains a diacritic character. 效果很好,直到json包含变音符号为止。 Where the content length then reports to be one character longer. 然后报告内容长度为一个字符长。 So obviously I have to get the actual json body. 因此,显然我必须获取实际的json主体。 This is proving difficult as calling request.getInputStream causes Jackson to fail as the input stream is already closed. 事实证明这很困难,因为调用request.getInputStream会导致Jackson失败,因为输入流已关闭。 Same for getReader. 与getReader相同。

So, I've done as outlined in this blog: http://natch3z.blogspot.co.uk/2009/01/read-request-body-in-filter.html 因此,我已经完成了此博客中概述的操作: http : //natch3z.blogspot.co.uk/2009/01/read-request-body-in-filter.html

Which works but doesn't properly encode to UTF-8. 哪个可行,但不能正确编码为UTF-8。 So I replaced this line: 所以我替换了这一行:

  bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

to: 至:

  bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

Which displays the correct json in my log, but I get this error when jackson tries to convert to a pojo: 它在我的日志中显示正确的json,但是当杰克逊尝试转换为pojo时出现此错误:

 nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0x9f 

I'm not sure how to get this working, if anybody has any ideas? 如果有人有任何想法,我不确定如何使它正常工作?

I just figured this out: 我只是想通了:

I replaced this line: 我替换了这一行:

final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());

with this: 有了这个:

final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes("UTF-8"));

I should have realized sooner, but this may help someone else with a similar issue. 我应该早点意识到的,但是这可能会帮助遇到类似问题的其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM