1

I am learning how to build Java WebApplications with Servlets. So far, I set up a Maven project with a Tomcat server and made a basic application with some forms up and running. But I got some basic questions:

  1. What is the difference between the doGet and doPost Methods of the Java Servlet Package? I understand the difference between request and response and I understand HTML GET and POST, but since the application works from the server side, I am confused.

  2. In the example below, why do I need the doPost methods which calls the doGet method (its from a tutorial I use)

  3. When I run the server and open it in the browser, I can submit the form using the button (see below). The button redirets me to /displayuserservlet which displays the first and last name I provided. If I then call /displayuserservlet manually, the first and last names displayed equal to "null". So why is the information not stored on the server (?) and how do I do it (in case that I wan't to store, e.g., a filepath/filename for later use).

My "website"/index.xml `form snippet:

<form action="/displayuserservlet" method="post">
   <center>
      First name:
      <input type="text" name="firstName" value="John">
      <br>
      Last name:
      <input type="text" name="lastName" value="Doe">
      <input type="submit"><!-- Press this to submit form -->
   </center>
</form>

My Servlet:

@WebServlet("/displayuserservlet")
public class DisplayUserServlet extends HttpServlet {

    //REQ is anything that comes FROM the browser
    //RES is anything sent TO the browser
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();//get the stream to write the data
        String title = "Results of form";
        String firstName = req.getParameter("firstName");
        String lastName = req.getParameter("lastName");

        //writing html in the stream
        pw.println(ServletUtilities.headWithTitle(title) +
                "<body bgcolor=\"#fdf5e6\">\n" +
                "<h1>" + title + "</h1>\n" +
                "<p>First name:" + firstName + "</p>\n" +
                "<p>First name:" + lastName + "</p>\n" +
                "</body></html>");

        pw.close();//closing the stream
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        doGet(req, res);
    }
}

Edited: code format

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Rubie
  • 13
  • 2
  • A very decent question for a new user dabbling in servlets. – Spectric Sep 16 '20 at 19:03
  • FYI: the `
    ` element is deprecated from HTML since 1998. Make sure you're reading sane and up to date tutorials.
    – BalusC Sep 16 '20 at 21:59
  • Thank you all for the detailed and helpful answers. So I currently realize, that maybe servlets are not state of the art anymore. It occurs to me, that the community went from servlets to JSP to JSF, is that correct? Then I maybe go over to JSF and look for tutorials on that :) – Rubie Sep 17 '20 at 08:10
  • In actuality, everyone at its core, as long as it's Java, relies on servlets. (Except for struts) So really, servlets are still the state of the art. – Spectric Sep 17 '20 at 16:25
  • Apples and Oranges. Servlets are just building blocks not complete MVC frameworks. It's absolutely essential to properly understand Servlets before diving into Servlet based MVC frameworks such as JSF. Else it will be harder understanding the MVC framework's inner workings. – BalusC Sep 17 '20 at 22:36

2 Answers2

0

doGet() and doPost() are called in response to GET and POST requests made by the client. If you want to handle GET and POST requests, but want to handle them in exactly the same way, you can have doGet() call doPost(), or vice versa as in your example. Or you can implement them differently, if you want to handle these request types differently. There are methods for other request types as well -- doPut() for the PUT request, and so on.

The method Request.getParameter() returns the value of a request parameter, that is, a value passed from the client in its request. If the client doesn't supply a value, this method return null. Nothing is stored on the server -- if you want data stored, you get to store it yourself. You can store it transiently, in a Session object, or more permanently in a database or some other storage system.

There are lots of good books on Java web programming. Trying to figure out how all the bits fit together by looking at 'hello, world' examples might not be the best way to get a handle on this very complex subject.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15
0

What is the difference between the doGet and doPost Methods of the Java Servlet Package? I understand the difference between request and response and I understand HTML GET and POST, but since the application works from the server side, I am confused.

In doGet Method the parameters are appended to the URL and sent along with header information. In doPost, parameters are sent in separate line in the body. ... doGet () method generally is used to query or to get some information from the server. doPost () is generally used to update or post some information to the server.

For example, a doGet() URL would look like this:

www.yourwebsite.com/servleturl?parameter1=smething&parameter2=smthingelse

A doPost() URL however, doesn't display the parameters in the URL, so it would just be:

www.yourwebsite.com/servleturl

You should always be using doPost for sensitive information such as a login or a payment form.

In the example below, why do I need the doPost methods which calls the doGet method (its from a tutorial I use)

This is called a POST-REDIRECT-GET. This is basically a feature that prevents the annoying 'Confirm Form Resubmission' message everytime you reload the page, and prevents users from executing an action twice by accident by reloading.

It's pretty hard to explain, but Wikipedia summarizes it very well.

When I run the server and open it in the browser, I can submit the form using the button (see below). The button redirets me to /displayuserservlet which displays the first and last name I provided. If I then call /displayuserservlet manually, the first and last names displayed equal to "null". So why is the information not stored on the server (?) and how do I do it (in case that I wan't to store, e.g., a filepath/filename for later use).

When you manually call /displayuserservlet, it's calling the doGet method. Unless you manually add the parameters in the URL (for example: /displayuserservlet?firstName=John&lastName=Doe which displays John Doe), the request attributes will all be null. Your program works just fine, but it doesn't print anything because you never submitted the parameters.

Spectric
  • 30,714
  • 6
  • 20
  • 43