Create Your First Web Application#

This tutorial has been made for students unfamiliar with creating web applications. It will familiarise you with IntelliJ, Java Servlet Pages (JSPs), Maven, and PostgreSQL.

For some people, this may be the first time you have encountered the tools we will be using in the project. Below is a list of extra resources you can use to become more familiar with them.

Tool

Use

Resources

GitHub

Version control

1. An interactive and visual tool to learn git commands: view
2. GitHub Learning Lab: view

Maven

Build automation tool

Learn how to use Maven in 5-minutes: view

Render

Platform as a Service (PaaS)

Developer Centre: view

PostgreSQL

Database

1. PostgreSQL tutorial: view
2. PostgreSQL tutorials and exercises: view

Java Database Connectivity (JDBC)

An application programming interface (API) for the programming language Java, which defines how a client may access a database.

Java Servlet Pages (JSPs)

Server-side programming technology that enables the creation of dynamic, platform-independent method for building Web applications.

Tomcat

Server and container to execute Java web applications.

Note

If you first want to learn the theory behind servlets, JSPs, and containers, check out JSPs and Servlets.

Create a Web Application in IntelliJ#

Please complete the below steps to create your first project:

Step 1: Install IntelliJ Professional Edition

Step 2: Download Tomcat

Step 3: Setup PostgreSQL

Step 4: Create Project in IntelliJ

Create a Servlet#

In this example, the project is titled ‘test’. Expand the directory as shown below and create a servlet:

We are going to create a LoginServlet:

Title the servlet LoginServlet and change the value to be ‘/login’ - the value becomes the URL of the servlet. For example, I can access the servlet by running the Tomcat configuration and navigating to: localhost.com:8080/login

In the doGet method, add the following code:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
    response.setContentType("text/html");
    System.out.println("Hello from Get method");
    PrintWriter writer = response.getWriter();
    writer.println("<h3> Hello in HTML</h3>");
}

Run the Tomcat configuration:

If a browser does not launch, open one and navigate to localhost:8080/<project_name>_war_exploded/login:

You will see the doGet() method you just edited:

You just created your first servlet!

Create a JSP#

Right click in the webapp directory to create a new JSP:

Enter a name for the JSP:

You have created your first JSP:

However, without a servlet to serve the JSP, it will not be accessible.

In the login JSP you just created, write something (it does not matter what). Something in the body, so it is visible when you navigate to the page:

Open the LoginServlet again and remove the code in the doGet() method and add the following:

response.sendRedirect("login.jsp");

Run the Tomcat configuration:

A browser window should automatically open. Navigate to: localhost:8080/<project_name>_war_exploded/login

The Login Servlet is now redirecting you to the login JSP you just created:

Passing Parameters to a Servlet#

There are two ways to pass parameters (arguments) to a servlet:

Create Connection with Local PostgreSQL#

Important

Make sure you launch pgAdmin and have the database instance running on your computer otherwise all queries will fail.

You should have already connected to a local PostgreSQL instance.
To open the database view:

Open a query console:

Run the follow SQL query to create a new table for users:

CREATE TABLE users (
    username text,
    password text
);

It should return successfully, and you should now be able to see the new table in the database view:

Run the following SQL query to create a test user:

INSERT INTO users(username, password) VALUES ('lrosa', 'test');

Create a new Java file and title it whatever you like:

Copy this to the newly created file but make sure to change the database URL, user, and password to match your own:

import java.sql.*;

public class JDBCtest {
        private final String url = <insert URL>;
        private final String user = <insert user>;
        private final String password = <insert password>;
        /**
         * Connect to the PostgreSQL database
         * @return a Connection object
         */
        public void connect() {
            String sql = "SELECT * FROM users;";
            PreparedStatement findStatement = null;
            ResultSet rs = null;
            Connection conn = null;
            try {
                DriverManager.registerDriver(new org.postgresql.Driver());
                conn = DriverManager.getConnection(url, user, password);
                findStatement = conn.prepareStatement(sql);
                findStatement.execute();
                rs = findStatement.getResultSet();
                rs.next();
                String username = rs.getString(1);
                System.out.println(username);
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        JDBCtest app = new JDBCtest();
        app.connect();
    }
}

Select Run:

It will take a few seconds to run but then should return a successful query:

You have now created a table in your local PostgreSQL instance, created a connection to it and queried data stored in the users table. You can now build queries on top of this.

Connect to Render PostgreSQL#

You must have completed Step 9: Deploy Project to Render before attempting this.

Now that you’ve deployed to Render, you must change the database credentials in order to access Render’s PostgreSQL instance.

Change the JDBCtest class to be:

try {
    DriverManager.registerDriver(new org.postgresql.Driver());
    String DB_CONNECTION = System.getenv().get("JDBC_DATABASE_URL");
    Connection dbConnection = DriverManager.getConnection(DB_CONNECTION);
    return dbConnection;
    } catch (SQLException e) {
        <write error message here>
    }
}

For more help, go to Render’s PostGres Documentation.