-1
public class CornelltaxiServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    resp.setContentType("text/plain");
    resp.getWriter().println("Hello, world");
}

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //resp.setContentType("text/plain");
    //resp.getWriter().println("Hello, world");
}

}

From my understanding of doGet and doPost, it shouldn't matter where I put the "Hello, world" message. However, when I try to print it using the doPost method, it does not work. Could anyone explain this for me?

Also, from

void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Preprocess request: we actually don't need to do any business stuff, so just display JSP.
    request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}

request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);

what does this do?

maxim 2
  • 91
  • 1
  • 8
  • How are you sending data? You need to submit a form for a doPost to be hit –  Mar 31 '12 at 19:45

1 Answers1

2

The doGet() method is called when HTTP GET is requested (e.g. when you type your servlets' URL in the browser). Then Hello, world will appear in the browser.

doPost() on the other hand will be used on HTTP POST. You need for example:

<form method="POST" action="/your/servlet"

When you submit such a form, you should see "Hello, world" (that is - when you uncomment it) in the browser as well.

As for your second question:

request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);

This will forward request processing to hello.jsp. Basically, the contents of that file will be rendered instead of your Hello, world. Sending both content using resp.getWriter() and forwarding is a mistake. Pick one.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674