Learn Servlet-JSP By Building A Social Network Website — Part III

Sera Ng.
Tech Training Space
7 min readOct 22, 2020

Understand the MVC architecture and configure our database connection for our project

Task 4: Reading: Model — View — Controller (MVC) architecture

As mentioned in the previous part, a servlet can handle many tasks such as generating HTML content, processing business logic, and connecting to a database system.

However, in real-life applications, we need to break our code into different components so that each component handles a certain task. That way, we can gain a lot of advantages:

  • Code is easily maintained
  • Code is easily reused
  • The program is easily scaled

The way the code is divided into separate components and each component plays a particular role is called software architecture.

MVC is one of the most popular software architectures, in which:

  • Model: performs business logics and data-related tasks such as connecting and executing SQL query
  • View: generate user interface so that end-users can interact with
  • Controller: receives requests from users and process accordingly

MVC architecture does not depend on any technology or framework. As long as you can break your code into 3 components that perform tasks as defined, then you can achieve the objectives of the architecture.

The main flow in MVC is as follows:

  • The Controller receives requests from the client such as a web browser.
  • If the request only requires a View, such as to request a login form, the Controller picks up the requested View and sends back to the client.
  • If the request is in need of processing business logic, such as checking login information, the Controller forwards the request to the Model to conduct necessary business logic. The Controller receives results from the Model and selects an appropriate View to respond to the client.
  • If the client requires a view filled with information, such as displaying a list of products, the Controller selects an appropriate View, the View connects to the Model to get data, the View then is sent back to the client.

In the Java web platform, we use:

- Servlet as Controller to handle requests from clients

- JSP, HTML, CSS, JS, and the likes as View to display results to clients

- Java classes as Model to handle main business logic and data manipulation

In our project structure, I have divided into packages and folders that conform to the MVC model:

Task 5: Config Database Connection

Before implementing any features, we need to configure our web application so that it can connect to the database system.

Since we are using My SQL 8, we will need the corresponding driver class for the task.

As explained previously, there is no need to download the driver-jar file, all we need to do is to add an xml-format dependency in the Maven file, which is the pom.xml file.

So, let’s open the pom.xml file in the Project Files folder.

There are a lot of auto-generated XML tags in the pom.xml file. But we don’t need to care about most of them.

The one we need to work with is the <dependencies> tag pair. So, locate these tags and add the following tags as its child tags:

Once added, your <dependencies> tags now look like:

But how do I know to add dependency tags, you may ask.

To find certain Maven format dependency, such as MySQL driver in our case, first, navigate to https://mvnrepository.com/

In the search box, type in the name of dependency you are looking for. For instance, I search for “mysql driver 8”

Then, select the corresponding library.

In my case, I pick the first one.

A list of versions will be showing up.

I’m using MySQL Server 8, so I need to look for the 8.0.x version.

But there are many 8.0.x versions as well. Which one to pick?

Usually, we should select the one with the highest usages.

As you can see in the Usages column, version 8.0.11 has the highest with 86 usages. So, I’ll get this one.

On this page, there are many tabs for different dependency management tools.

Since we are using Maven, we just need to copy the tags in the Maven tab and paste to our pom.xml file as we’ve just done.

Next, we need to download the dependency jars in order to use the libraries in our code.

In the project structure, right-click on the Dependencies item, and select Download Declared Dependencies

Then, wait for Netbeans to download declared dependencies. Depending on your network capacity, but usually it should take a couple of seconds.

Once Netbeans has finished the download, expand the Dependencies item, you will see the declared library has been added.

Next, we need to define the information for database connectivity.

Open the web.xml file in the WEB-INF folder, then add the following tags inside the <web-app> tags:

Except for the db.driver value that should be kept the same, you should change the values of db.url, db.user, and db.password according to your environment settings.

The final web.xml should look like this:

The reasons I have placed database configuration in the web.xml are that:

  • It is easy to change once we deploy our web application on the production server
  • It is easy to read these configured values in our code. These configurations are global which means they can be read by any servlet related instances.

Before reading these database-configured values, we need to declare variables in our code to be ready to store these read information.

In the net.learnbyproject.service package, create a new Java class called DBService with the following contents:

The 4 variables DRIVER, URL, USER, and PASSWORD are used to store configurations read from the web.xml.

These variables then will be accessed by the openConnection() method to establish a connection to the database system.

Next, let’s write code to read database configurations in the web.xml.

There are different ways to achieve such a task. But I would prefer to use Event Listeners for the sake of convenience.

Event Listeners provide a way to track key events in your web application such as:

  • When our web application first starts or is destroyed
  • When a session is created or destroyed
  • When a request is created or destroyed

Since we only need to read database configurations once and use them throughout the entire application, using Context Listener should be the appropriate choice.

The Context listener is triggered in 2 events:

  • The first one is when the application first starts. This is what we need.
  • The second one is when the application stops

In the net.learnbyproject.listeners package, create a new Java class called AppListener with the following contents:

The @WebListener() annotation indicates that this Java class will act as a web listener.

To specify what kinds of events should be triggered, which the application starts and stops in our case, the interface ServletContextListener should be implemented with the 2 corresponding overridden methods.

And since we only need to read data configuration when the application starts, the implementation of the contextInitialized() method is sufficient.

We invoke the getInitParameter() method parameterized with the name to get the corresponding value.

And then, we test if the connection can be established successfully.

If it can, we print out the database name:

System.out.println(“Connected to : “ + connection.getCatalog());

Before running the application, since we have added new classes, we should clean and build our application first:

Then, we should stop and un-deploy the previous version:

Now, let’s run the web application again:

And if everything has been done right, open the Apache Tomcat Console, you will see the line:

>> Read Part IV

--

--