我有2个网络应用程序,两个都没有前端(即html / Jsp)。两者都有一个servlet。
让我们将它们称为WebApp1 / WebApp2和ServiceServlet1 / ServiceServlet2。
我有2个war文件,WebApp1.war和WebApp2.war,并且都已部署。

我直接使用以下命令从浏览器中调用ServiceServlet1:
http://localhost:8080/WebApp1/ServiceServlet1
显然,将调用doGet方法(POST仅与FORM相关联,如果我错了,请纠正我)。
ServiceServlet1的构建类似于-

    public class ServiceServlet1 extends HttpServlet {
     @Override
     protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
       throws ServletException, IOException {
      doPost(httpRequest, httpResponse);
     }

     @Override
     protected void doPost(HttpServletRequest httpServletRequest,
       HttpServletResponse httpServletResponse) throws ServletException,
       IOException {
      RequestDispatcher requestDispatcher;

      try {
// Process something
       requestDispatcher = getServletContext().getRequestDispatcher("/WebApp2/ServiceServlet2");
       requestDispatcher.forward(httpServletRequest, httpServletResponse);
      } catch (IOException ioException) {
       ioException.printStackTrace();
      } catch (ServletException servletException) {
       servletException.printStackTrace();
      }
     }
    }


本质上,我需要的是调用doPost()ServiceServlet2
我用httpReq.getRequestDispatcher()sendRedirect等尝试了几种不同的方法,但到目前为止都失败了。

那么我该如何实现呢?

谢谢。

最佳答案

除了ckuetbach的答案之外,您在分派请求时不能更改请求方法。如果第二个servlet也不能更改为在doGet()上执行相同的业务逻辑,那么您必须以编程方式自行触发POST请求。

HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost/WebApp2/ServiceServlet2").openConnection();
connection.setRequestMethod("POST");
InputStream response = connection.getInputStream();
// ... Write to OutputStream of your HttpServletResponse?


也可以看看:


How to use URLConnection to fire and handle HTTP requests?

07-24 12:41