Search code examples
javajspservletsresponse

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


I wondered if it is possible to send HTML page using both Servlet and JSP. And no, I don't want JSP to do all work by forwarding the request from Servlet. I want Servlet to write "hello" and JSP to write "user's name".

This is my try, which failed:

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>

After filling my form:

enter image description here

, I expected to get hello elephant. But I only get elephant. I tried to put pw.flush() inside servlet's code which gave an opposite result - just hello.

Now I am stuck, as I don't understand what is wrong. I guess when I flushed a stream, response was committed, so rest of code didn't run. But why user didn't get hello message when I didn't commit (flush) a stream? Can I even do such a thing as I described? Looks like I am missing some elementary things here.


Solution

  • Use RequestDispatcher.include(ServletRequest, ServletResponse) instead of forward. Change

    dispatch.forward(req, resp);
    

    to

    dispatch.include(req, resp);