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

This is the fourth in a series of articles. Here you can find the previous part: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #3

What could have gone wrong so far?
We continue the development of our sample web application focusing for a moment on what problems we might encounter with the capabilities that we have implemented and the errors that may occur in the code and configurations developed so far.
We see, for example, the effects of a wrong configuration of drivers for the relational databases (PostgreSQL in our case) in the Hibernate configuration files, rather than attempting to make a getParameter for a parameter that does not really exist in the object HttpServletRequest. We’ll see also an error due to the violation of a constraint defined on the table during an insert of a new record.

Hibernate configuration error
A possible error that we consider is what happens if we fail to enter the Hibernate configuration information related to the RDBMS (Relational DataBase Management System) that we want to use and the credentials to access the instance of our database in “hibernate.cfg.xml” file.
Suppose, for example, to erroneously configure the use of PostgreSQL, setting in the wrong way the property hibernate.connection.driver_class. Let’s go to the Hibernate configuration file and then replace the line

org.postgresql.Driver

with the line

com.postgresql.Driver

(It is also a mistake really already seen, the result of a copy/paste from a previous driver configuration for MySQL in which, switching to PostgreSQL, it has remained the “.com” extension instead of “org”)

Hibernate cfg xml Driver error
Running our application with this configuration of course we get an error that tells us that it’s not able to find the driver for the database that we have indicated:

Grave: Servlet.service() for servlet [com.dede.app1st.controller.AddUser] in context with path [/WebTest] threw exception
org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.postgresql.Driver]

The following image illustrates the result that Tomcat shows us:
Hibernate cfg xml unable to load Driver class

Another possible error is related to the fact that the credentials for access to the database included in the Hibernate configuration file are incorrect. If we try for example to change the value of the property “hibernate.connection.password” by assigning the value “davis” instead of “dede”, which is the password that we defined during the database creation, we get the following exception:

Grave: Servlet.service() for servlet [com.dede.app1st.controller.AddUser] in context with path [/WebTest] threw exception
org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
. . .
. . .
Caused by: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"

The following picture shows again the error:
Web Application Hibernate wrong password

Get a parameter that does not exist in the request
Another mistake we can make in the code developed so far (in previous articles) is to try to extract from the request the value of a parameter giving a wrong value for the parameter name.
We have extracted the value of a parameter from the HttpServletRequest invoking on the latter the getParameter method, defined in the ServletRequest interface implemented by HttpServletRequest, to which we passed each time the name of the parameter that we wanted to extract the value of (“firstname”, “lastname”, etc ..). SO, to understand what happens if we specify as an argument of the getParameter method the name of a parameter that does not exist in the request we can look at how this method is defined and described in the official JavaEE documentation:

        String getParameter(String name)

Returns the value of a request parameter as a String, or null if the parameter does not exist.

As we can see then, if we ask to the getParameter method to retrieve from the request the value of a parameter that does not exist, it returns a null vallue, without triggering any kind of exception or generate any error.
Let’s see an example:
Let’s go back to the first version of our application, the one where we had not yet introduced the storage into the database of the information related to the new user created. This version was limited to display on-screen user information, sent through the input form, by using the jsp page “useradd”. To do this, we go to the doPost method of our servlet and comment the part relating to the creation of the new User object and its insertion in the database through the Hibernate classes.

web application servlet
Now, let’s try to modify the “useradd.jsp” file by changing the name of the parameter we want to retrieve the value using the getParameter method from “firstname” to “first”. This obviously does not exist because in the form through which we submit the values the name remains “firstname”.
HttpServletRequest parameter not existent

Now we start again our application, enter the data in the input form and submit it. What we expect, as we had already seen, it is that the JSP page shows us the data we entered.
Web Application input form
As we can see in the follwing picture, in correspondence of the “First Name” field we can see a null value instead of the value that we placed on the input form. This is because the getParameter method, finding no parameter called “first”, it returns in fact null.
Web Application null parameter value
Now, let’s see a second example, in which we restore our application to the current version that handles requests by entering new users into the database and modify again the name of a parameter that we ask to HttpServletRequest using the getParameter method, passing it a name that does not exist. In this case we replace the name of the “country” parameter with “coun” inside the doPost method of our servlet, at the point in which we use the information sent with the request to instantiate the new object of the User class.
We instead leave unchanged the getParameter calls inside the JSP page “useradd”, which then successfully retrieve the values of all three parameters.
Web Application request parameter not existent
After making these changes we run again our application, we compile as usual the input form with the user data to create and we send the request.
Web Application input form

The result we get is that shown in the figure below, in which:

  • The requested operation completes successfully, and we don’t get any error or exception
  • The record for the new user is inserted in the database but the “country” field is set to null instead of being valued with the string “Argentina” that we had entered in the input form. This is because the getParameter method, having been invoked by giving as argument the name of a nonexistent parameter (“coun”), returns null and this value is passed to the constructor of the User class to instantiate the new object. The instance variable “country” of the new object is then set to null and this value is reported by Hibernate in the database when performing the insert statement. In this case it is not a problem, because we defined the “country” column in the database as nullable, indicating that we would allow records (and then objects) in which it has not been set.
  • In the JSP page instead we can see how the “Argentina” value of the “country” parameter is shown correctly. This is because the JSP page “useradd” performs in turn the retrieve of the request parameters with the getParameter method indicating for all parameters, including “country”, the correct name. We will see further on how to prevent the JSP page reads again the parameter values sent through the form, already acquired by the servlet and included in the User object created. We will make sure that the servlet will pass directly the User object to the JSP page using the setAttribute method of the request.
  • Web Application database null value

    Finally we see a third example, similar to the one just seen where, however, the parameter for which we provide the wrong name to the getParameter method is a field that in the database is defined as not nullable. In our “AddUser” servlet then we restore the call getParameter(“country”) and modify instead the call getParameter(“firstname”) in getParameter(“first”) so that we try to retrieve the value of a parameter that does not exist. The code of the class for this test then becomes as in the following image.
    Web Application request parameter not existent

    Again, we fill out the form with the information of a new user we want to enter …
    Web Application input form

    What we get in this case is an error of violation of a database constraint, as we are trying to insert a row, and then an object, that has a null value in one of the fields (firstname) that we had defined as not nullable when created the database table.
    As we can see from the image below, Hibernate in this case triggers a PropertyValueException and gives us details on the error type and an indication about which field of which class has generated the problem.
    In fact, we get for our example

    Grave: Servlet.service() for servlet [com.dede.app1st.controller.AddUser] in context with path [/WebTest] threw exception
    org.hibernate.PropertyValueException: not-null property references a null or transient value : com.dede.app1st.model.User.firstname
    

    that indicates us that the instance variable “firstname” of the “User” class is null and we’re trying to put it in a column of a database table that doesn’t allow null values.

    Web Application insert database constraint  violato

    You can find the next part of this tutorial here: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #5

    See also:

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

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

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

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

  3. Hello Sir,

    I have tried to implement the sample application by following your instruction, but I am struck with the error
    HTTP 500- Unknown entity :com.opms.model.User
    Please tell me where I have gone wrong.

    PS : I have tried the exact steps that you have provided in the website

    • Hi,
      if you’re sure your entities mapping is correct this error is in general due to the use of a different Hibernate version. Which version are you using?
      In case you’re using a most recent Hibernate version, in order to fix you error you can explicitly add your annotated entity class to the Configuration.
      Try to modify the doPost method in this way (the line in the middle is the new one):

      Configuration config = new Configuration().configure();
      config.addAnnotatedClass(Users.class);
      ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
      

      Please let me know if this solved your issue.

      Davis

  4. hi. can you please help me retrieve the data from the table? your tutorial helped me a lot. thank you. i am new to hibernate. but after your tutorial, i cannot find anything on this topic.

Leave a Reply to Mark Cancel reply

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