UTF-8 用于 Restful 服务
目前,我在 RESTful 服务中为不同的方法启用 UTF-8 作为 @Consumes("application/xml;charset=utf-8") 。我很想知道我们是否可以通过一次配置更改来更改所有 REST 服务的这一点。我们正在使用CXF,也许它提供了一些东西?
谢谢 拉维
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个问题是您确定要阻止任何其他资源接受非 UTF-8 实体吗?如此全面的声明感觉可能会在未来带来麻烦。
我承认我没有使用过 CXF,所以我无法谈论这些细节。但我可以在 JAX-RS 和 Servlet API 下分别想到一个选项,这可能符合您想要实现的目标。
使用 Servlet API:根据您部署应用程序的方式,您可能能够创建并注入 servlet 过滤器。在 doFilter 方法中,您可以检查请求实体的编码,并继续处理过滤器链的下一部分(最终到达其余应用程序)。如果请求中发送了不正确的实体,您只需在响应上设置适当的 HTTP 415 状态,而不会调用其余应用程序。
使用 JAX-RS:根据您解析/接受资源中的实体主体的方式,您可以创建并注入自定义 MessageBodyReader 实现。该阅读器可以解析您的实体,确保它仅为 UTF-8,否则抛出适当的异常。
The first question is are you sure you want to prevent any of your rest resources from accepting non-UTF-8 entities? Such an across the board proclamation feels like it could cause trouble down the road.
I'll admit that I haven't used CXF so I can't speak to those specifics. But I can think of one option each under the JAX-RS and Servlet APIs which might be along the lines of what you seek to accomplish.
Using the Servlet API: Depending on how you are deploying your application you might be able to create and inject a servlet filter. In the doFilter method, you can check the encoding of the request entity and continue on to the next part of the filter chain (ultimately to the rest application). If an improper entity is sent on the request, you would just set the appropriate HTTP 415 status onto the response and not invoke your rest application.
Using JAX-RS: Depending on how you parse/accept the entity body in your resources, you could create and inject a custom MessageBodyReader implementation. This reader could parse your entity, ensuring that it is UTF-8 only and throw an appropriate exception otherwise.