如何在一个servlet中调用另一个servlet?
正如标题提到的,如何在 servlet 中调用另一个 servlet 并获取调用的 servlet 响应?
As title metioned, How to invoke another servlet in a servlet and get the invoked servlet response?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
RequestDispatcher
实例可通过 HttpServletRequest 实例获得。但是,如果您希望获取 servlet 容器所持有的单个实例 [例如使用
ServletContext
实例中的getServlet
方法],这是一个完全不同的故事。 Servlet 规范有意弃用了可能允许此类选项的操作。但是,如果您确实想要在执行另一个 servlet 的同时调用一个 servlet,请使用RequestDispatcher
的include
方法,而不是转发方法。
Use
RequestDispatcher
instance which is available through theHttpServletRequest
instance.However, if you're looking at getting hold of the single instance held by the servlet container [like using the
getServlet
method in theServletContext
instance], it's an entirely different story. The servlet specs have purposefully deprecated the operation which might allow such an option. But, if you really want to invoke one servlet while executing the other one, use theinclude
method of theRequestDispatcher
instead of theforward
method.请参见此处:
不过我认为还有更好的选择。例如,将您需要的代码移动到辅助类/实用程序方法中,然后调用它。
我想起来,您可能还想要另一件事:单独调用 servlet。为此,您需要:(
这是使用 apache commons-io 将输入流复制到当前请求的输出流)
See here:
However I'd assume there are better options. For example move the code you need to a helper class / utility method, and invoke it.
As I come to think of it, you may want another thing: call a servlet separately. For that you need:
(this is using apache commons-io to copy the input stream to the output stream of the current request)
使用ServletContext或者当前请求获取RequestDispatcher,然后使用RequestDispatcher的forward()或者include()。
可以使用 Spring MockHttpServletRequest 和 MockHttpServletResponse 创建新的请求和响应,而不是使用当前请求。
例子:
Use ServletContext or current request to get RequestDispatcher, and then use RequestDispatcher forward() or include().
Can use Spring MockHttpServletRequest and MockHttpServletResponse to create new request and response instead of use current request.
Example:
此外,您可以直接从 JSP 发送参数:
Furthermore you can sending a parameter like directly from JSP: