O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

POST is NOT the default!

If you don’t put method=“POST” into your form, the default is an HTTP GET request. That means the browser sends the parameters in the request header, but that’s the least of your problems. Because if the request comes in as a GET, that means you’ll run into big trouble at runtime if you have only a doPost() and not a doGet() in your servlet!

If you do this:

image with no caption

And then this:

public class BeerSelect extends HttpServlet {

   public void doPost(HttpServletRequest request, HttpServletResponse response)
                                             throws IOException, ServletException {
     // code here
   }
}

Note

No doGet() method in the servlet.

You’ll get this:

Note

FAILURE! If your HTML form uses GET instead of POST, then you MUST have doGet() in your servlet class. The default method for forms is GET.

Q:

Q: What if I want to support both GET and POST from a single servlet?

A:

A: Developers who want to support both methods usually put logic in doGet(), then have the doPost() method delegate to the doGet() method if necessary.

public void doPost(...)
                throws ... {
   doGet(request, response);
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required