How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #2

This is the second in a series of articles related to the development of a simple web application. Here the Part 1

DESIGNING THE FIRST APPLICATION
In this section we will begin to expand our application with different components introducing a new page containing a form for the insertion of input data by the user, creating our first servlets and connecting to a database for storing data. Specifically, the functionality we want to add to our application is the ability to create users and store their information in a database, in order to have access to them at any time. The first thing to do, therefore, is making a diagram of this new feature we want to add and identify the objects that will help us to implement it and the interactions between them.
The figure below shows the schema for the “create user” functionality of our application:

Create a simple web application - part2

Creating a user will then go through the following steps:

  • The user lands on the homepage
  • From the homepage, the user can click on “Create New User”
  • This will open a new page with a form for entering user data
  • The user clicks the “create” button
  • The http POST request is sent to the Servlet called AddUser
  • The Servlet inserts data about the user just created in the database
  • The servlet forwards the request to a JSP page
  • The JSP page indicates that the user has been created and shows its information

CREATE THE INPUT FORM
Let’s start by creating the new page that will contain the form for data entry.
In our Eclipse project we right click on the WebContent folder, select the “New” item in the context menu, then choose “HTML file”. We insert in the wizard that appears the name of our new page, “createuser.html” and then we click “Finish” (For the moment we just skip the choice of the DTD – Document Type Definition to use).
Insert in the new page the code for the creation of the form fields in which the user must enter data for its registration. Having defined the USER object as consisting of three values of type string, let’s put on our webpage their relevant input areas and the button to send to our servlet the information contained in the form.

<form method="POST" action="CreateUser.do">
First name: <input type="text" size="40" maxlength="40" name="firstname"/><br>
	Last name:  <input type="text" size="40" maxlength="40" name="lastname" /><br>
	Country:    <input type="text" size="40" maxlength="40" name="country"  /><br> 
	<input type="SUBMIT" value="create">
</form> 

The following picture shows the new page created within the Eclipse project and its source code, containing the input form.

Create a simple web application - input form

Now that we have created the new page we can restart the application and see if the page is reached by the link located on the home page and displayed correctly.
If what we have done is correct, the result we get is the one shown in the following picture:

Create a simple web application -  input form test

CREATE THE FIRST SERVLET
The next step is to create the servlet who will process the request to create a new user, that will be mapped (more about this topic in a very short) to the target address previously specified by the “action” attribute of the “form” tag and invoked once the user presses the “create” button. To do this we right click on our project, select “New” from the contextual menu, then select again “Servlet”, as shown:

Create a simple web application - new servlet

At this point it opens the Eclipse wizard shown in the following picture, in which:

  • The “Source folder” field is pre-filled with the path of our source file folder, ie “/WebTest/src” and we keep this value.
  • We insert the name of the package we created, where we want then to insert our servlet class: com.dede.app1st.controller
  • We insert the class name of our Servlet, called AddUser
  • The “Superclass” field is pre-filled with the name of the class our servlet class must extend

Create a simple web application - new servlet

Let’s click on “Next” button and proceed with the creation of our Servlet: insert a description of our servlets in the field called “Description” as well and insert the URL on which our servlet will be mapped. The latter operation requires a bit of attention, because the URL we enter must match exactly the one we have referenced in the “action” attribute of the “form” tag in our createuser.html web page.

	<form method="POST" action="CreateUser.do">

Eclipse, by default, gives us the mapping of the servlet with the URL that contains the name of the servlet, in this case “/AddUser”. So, having previously indicated in the form the path “CreateUser.do” as the target, we have to click “edit” and to change the URL pattern to be mapped from “/AddUser” to, in fact, “/CreateUser.do”.
This operation is illustrated in the following picture, in which it is underlined the congruence between the URL pattern defined during the servlet creation and the “action” field of the form:

Create a simple web application - create servlet

Clicking on “Next >” button we reach the last step of the servlet creation wizard where we choose methods for which we want Eclipse to generate stub, that is, the method prototype ready to fill with our implementation. In this case, having specified in our form that request will be of type “POST”, setting the “method” attribute as follows

         <form method="POST" action="CreateUser.do">

we must implement the relevant method of our servlet that will take care of this kind of request, that is, the doPost method.

Create a simple web application - new servlet

The signature of doPost method, inherited from HttpServlet superclass, is the following:

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException

and Eclipse already put it in our servlet class, as shown here:

Create a simple web application - servlet classes missing

But, wait a moment: the AddUser class that represents our servlet, generated from Eclipse after the end of the wizard we have followed, has several compilation errors due to the impossible resolution of all classes belonging to the Servlet API, and their related import.

In fact, if we go with the mouse over one of the classes outlined in red, we can see the error

HttpServletRequest cannot be resolved to a type

This is due to the fact that we have created in Eclipse first our web project and only after we have configured the Tomcat server on which to run it. In this way we said to our application which instance of Tomcat to use when launched (to see the Server set to run the application we must go on the set of properties, called “Server”, as shown in the picture), but we didn’t specify to use the Tomcat runtime environment.

Create a simple web application - Tomcat server setting

HOW TO SET THE RUNTIME ENVIRONMENT
To set the runtime environment we need to right-click on our project, select from the contextual menu the “Build Path” item and then select “Configure Build Path”:

Create a simple web application -

At the point the window with the properties of our project appears, and it displays as default properties for the “Java Build Path” set (list of properties sets on the left panel of the window). We can observe, in the picture below, the content of the tab “Libraries”.

Create a simple web application - Build Path settings

Now we click on the “Targeted Runtimes” set, select “Apache Tomcat v7.0” and press the “Apply” button:

Create a simple web application - targeted runtimes

At this point, if we go back in the set of properties “Java Build Path” to the tab “Libraries”, we see that there is a new entry in the list, called “Apache Tomcat v7.0”:

Create a simple web application - tomcat libraries

If we drill down this item we see the list of Tomcat libraries that at this point are included in our project and in the list we can also find the library “servlet-api.jar” that previously was missing:

Create a simple web application - tomcat libraries

If we go back to our Servlet class, Add User, we see that all of the compilation errors are gone, because the imports are now resolved and the Servlet API classes are “recognized”.

Create a simple web application - servlet imported

HANDLING THE REQUEST
Now that we have defined and mapped our servlet we have to tell them how to process the requests that reach her, for the moment as form submissions via the post method. To do this, as we have seen, we have to provide the implementation of the doPost() method.
Earlier, in the “DESIGNING THE FIRST APPLICATION” section, we defined that the way we want our simple application processes the request is to tell us that we have created a new user and show its related data (sent through the form).
This result must be displayed by a JSP page , to which the servlet will forward the request. In this way we implement the MVC (Model-View-Controller) pattern separating the Controller (Servlet) from the view (JSP).
To delegate, within the servlet, the request handling to a JSP we have to use a RequestDispatcher, which is obtained by invoking the getRequestDispatcher method on the HttpServletRequest input object, specifying as parameter to which component we want to route the request to.
For example, to indicate our JSP page as receiver of the request forwarding, we need to do this way:

RequestDispatcher view = req.getRequestDispatcher("useradd.jsp");

To actually send the request, we invoke the forward() method on the RequestDispatcher object previously obtained, passing to it the original request (HttpServletRequest) and response (HttpServletResponse) as parameters:

view.forward(req, resp);

The following picture shows the doPost() implementation of our servlet:

Create a simple web application - servlet doPost method

CREATE THE JSP PAGE
At this point we must create the JSP (Java Server Page) who will process the request that will be forwarded it by the servlet. To do this we go in the Eclipse side panel “Project Explorer”, select the “WebContent” folder and right-click it. In the contextual menu that appears we choose “New” and then “JSP”. (If the “JSP” is not immediately available in the contextual menu, select “Other”, enter as the search string “JSP” and choose “JSP File” from the suggested results).

Create a simple web application - create new JSP

In the creation wizard that opens we indicate the name of our page, which will be “useradd.jsp”.

Create a simple web application - create new JSP

In this way we create, under the “Web Content” folder , our brand new JSP page, which looks like this:

Create a simple web application - new JSP

At this point we must insert into our JSP the code to process the request received from the servlet. We must then retrieve the information from the request, that is, from the HttpServletRequest object received as input by the Servlet and in turn forwarded to the JSP through the forward() method. To do this we must use the getParameter method of the HttpServletRequest object, defined as follows:

String getParameter(String arg0)

This method takes as parameter a string that represents the name of the request attribute of which we want to retrieve the value and it returns a string that contains this value.
In our example, we use it to retrieve the values of the fields entered by the user in the form that he has submitted.
Our form contained three fields:

<form method="POST" action="CreateUser.do">
        First name: <input type="text" size="40" maxlength="40" name="firstname"/><br>
	Last name:  <input type="text" size="40" maxlength="40" name="lastname" /><br>
	Country:    <input type="text" size="40" maxlength="40" name="country"  /><br> 
	<input type="SUBMIT" value="create">
</form>

So, we must invoke the getParameter() method on the object request once for each of the parameters we want to retrieve the value. The value that we have to pass as a parameter is the “name” that we have assigned to the form components. To retrieve, for example, the value that the user entered in the “firstname” field we must use the following code:

First Name: <% String fName = request.getParameter("firstname"); out.print(fName); %>

The following picture shows the code of our JSP, modified to retrieve the data in the request and show a page for the successful user creation with such data:
Create a simple web application - jsp getParameter

Now let’s run again our application. So, from the Eclipse toolbar or from the contextual menu select “Run as” and then “Run on Server”. We expect to see in Eclipse the homepage of our application, as we had already seen in the section “THE FIRST EXECUTION OF THE PROJECT.”

Create a simple web application

Click again on the “Create new user” button, enter the data for creating the user and then submit the form.

Create a simple web application  - input form

The request is routed to the url to which our servlet is mapped to and forwarded to the JSP page that processes it and, as expected, it shows us the message of the successful creation of the user with its own attributes value.

Create a simple web application  - new record created

Well, the result is what we expected, so we have our first servlet and our JSP working correctly and able to process requests.
The next step will be to introduce another layer in our architecture, represented by a relational database that will allow us to save and to persist data in our application, and precisely to save in a table information related to our users. We will also imrpove the implementation of the MVC paradigm, introducing the Model of our “User” objects, on which we have glossed over so far, retrieving the information directly from the request and focusing only on their exchange.

Go to the third part: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #3

This entry was posted in $1$s. Bookmark the permalink.

3 thoughts on “How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #2

  1. Pingback: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #1 | Dede Blog

  2. Pingback: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #3 | Dede Blog

  3. Pingback: How to create a Servlet: Annotations (Servlet 3.0) vs. XML (up to Servlet 2.5) | Dede Blog

Leave a Reply

Your email address will not be published. Required fields are marked *