将请求信息从 Servlet Filter 传递到 Web Service
我需要从 Web 服务中检索 HTTP 标头中发送的一些信息。我怎样才能实现这个目标?
I need to retrieve some information sent in the HTTP headers from within a Web Service. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您要使用的语言和 Web 服务框架。
您的问题标题提到“Servlet Filter”,因此我假设您使用 Java 应用程序容器。如果您的 ws 框架不支持将请求标头映射到值对象,您可以使用 Servlet Filter 来处理标头并将信息存储在以后可以检索的地方。最好的选择是将其放入请求属性中。如果您稍后无法访问 HttpServletRequest(这可能会让您提出这个问题),您可以将其存储到 ThreadLocal 变量中,但这比较棘手。
我将给您一个最小的示例:
它可以工作,但在现实生活中的实现中,您应该在 ThreadLocal 中存储您自己的类的对象(例如 Bean),而不仅仅是一个字符串。您应该考虑将 ThreadLocal 变量放在过滤器之外(例如,作为静态变量放在更合乎逻辑的地方)。
It depends on the language and web service framework you want to use.
Your question title mentions "Servlet Filter" so I assume you work with a Java application container. If your ws framework does not support the of mapping request headers into value objects, you could use a Servlet Filter that processes the header and stores the information somewhere you can retrieve it later. The best option would be to put it in a request attribute. If you can't get to the HttpServletRequest later (which probably makes you ask this question), you can store it into a ThreadLocal variable, but this is trickier.
I'll give you a minimal example:
It works, but in a real life implementation you should store an Object of your own Class in the ThreadLocal (e.g. a Bean) instead of a mere String. You should consider putting the ThreadLocal variable outside your Filter (e.g. as a static variable somewhere in a more logical place).