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:
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 the example below, why do I need the doPost methods which calls the doGet method (its from a tutorial I use)
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