如何制作一个简单的程序,其中 Servlet 和 JSP 一起生成 HTML 文件?

How to make a simple program where both Servlet and JSP together generate HTML file?

我想知道是否可以使用 Servlet 和 JSP 发送 HTML 页面。不,我不希望 JSP 通过 转发 来自 Servlet 的请求来完成所有工作。我想让 Servlet 写“你好”,JSP 写“用户名”。

这是我的尝试,失败了:

index.html:

<html><body>
    <form action="MyServlet" method="POST">
        Enter name: <input type="text" name="name">
        <button>Submit name</button>
    </form>
</body></html>

MyServlet.java:

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = resp.getWriter();
        pw.println("hello ");

        RequestDispatcher dispatch = req.getRequestDispatcher("test.jsp");
        dispatch.forward(req, resp);
    }
}

test.jsp:

<html><body>
<%= request.getParameter("name") %>
</body></html>

填写我的表格后:

,我预计会得到 hello elephant。但是我只得到elephant。我试图将 pw.flush() 放入 servlet 的代码中,结果却相反 - 只是 hello.

现在我卡住了,因为我不明白哪里出了问题。我想当我刷新一个流时,response 被提交,所以其余代码没有 运行。但是为什么当我没有提交(刷新)流时用户没有收到 hello 消息?我什至可以像我描述的那样做吗?看来我在这里遗漏了一些基本的东西。

使用 RequestDispatcher.include(ServletRequest, ServletResponse) 而不是 forward。变化

dispatch.forward(req, resp);

dispatch.include(req, resp);