Building Your First Java Web Application: A Step-by-Step Guide

First Java Web Application using NetBeans, Apache Tomcat, MySQL

Learning Objectives:
- Creating Java Web Application using Apache NetBeans
- Establishing JDBC connection
- Developing User Login procedure
- Application deployment and testing

Technology:
- Apache NetBeans IDE 23
- Java 22.0.1 64-Bit Server
- Java SE Runtime Environment 22.0.1
- OS Windows 11
- Web Server Apache Tomcat 11.0.1
- Servlet Version: 6.1
- JSP Version: 4.0
- MySQL Community Server 8.0.20

Detailed Procedure:

Environment Setup Requirements:

Apache NetBeans Download: https://archive.apache.org/dist/netbeans/netbeans-installers/23/Apache-NetBeans-23-bin-windows-x64.exe

Java Download:
https://download.oracle.com/java/22/archive/jdk-22.0.1_windows-x64_bin.msi

Apache Tomcat:
https://dlcdn.apache.org/tomcat/tomcat-11/v11.0.2/bin/apache-tomcat-11.0.2-windows-x64.zip

MySQL:
https://downloads.mysql.com/archives/get/p/23/file/mysql-8.0.20-winx64.zip

File → New Project → Categories → Java with Maven → Projects → Java Web Application

When you click Finish, Netbeans will start creating the project that will take a few seconds. Finally you will see the project created automatically in the left pane under tab Projects. Also in the Output window under Project Creation tab you will see the message ending with the given text:

This message ensures the project has been created successfully.

Re-test compilation:

Select the newly created project LoginApp-1.0 and right click with mouse and select Clean and Build. You will notice the BUILD SUCCESS message appears again.

Web Server integration:

Under the folder C:\DevSpace\DevJava\LoginApp create a folder with the name server. Now copy the Apache Tomcat file apache-tomcat-11.0.2-windows-x64.zip to the server folder. Now extract the ZIP file and ensure the folder bin is available: C:\DevSpace\DevJava\LoginApp\server\apache-tomcat-11.0.2-windows-x64\apache-tomcat-11.0.2\bin

On the left pane click on Services tab and select Servers. Right click on Servers and select Add Server…

As shown in the above image select option Apache Tomcat or TomEE and click Next.

Provide the Server LocationUsernamePassword as shown above. However it will show an error message The specified Server Location (Catalina Home) folder is not valid.

Modify the Server Location by removing the bin at the end.

Now you will notice the error is removed and the Finish button is enabled. Click on Finish button and you will see the server is added as below:

Test Run the Server:

Select server Apache Tomcat or TomEE and right click and select Start. You will notice the Servers expandable as shown below with server named marked with green symbol indicating server is started.

Now open a new browser window and provide the URL http://locathost:8080/. You will notice the Apache Tomcat Home screen is displayed as below. This indicates the server is installed and working fine.

Now you can stop the server by selecting server name Apache Tomcat and TomEE in the left pane and select Stop by right clicking options. Now come back to the browser and click refresh on the page ensuring the same URL http://locathost:8080/. Now you will notice the message This site can’t be reached. This is because the server has been stopped.

Testing Application Deployment on Server:

Select the created project LoginApp-1.0 on the left pane and select Properties by the right click.

In the Project Properties window select Apache Tomcat and TomEE under the Server dropdown. Select Chrome under the Browser dropdown. This will set the default browser for your application. You can set any other browser of your choice.

The final setting will appear as shown above and then click OK. This will automatically configure the web server Apache Tomcat with your LoginApp-1.0 web application.

Select the created project LoginApp-1.0 on the left pane and select Clean and Build by right click. And then select Run by right clicking on the project.

You will notice the Chrome browser page is opened automatically and will display the message Hello World! as shown above. This indicates your web application has been created and deployed successfully on the server.

Start developing Login Application:

In the Projects view select folder Web Pages, right click and select New → JSP. This will open the window as shown below.

Notice this JSP will be created under the Location Web Pages. Make sure you create all the other JSP under this location. Now click Finish. You will notice the JSP file is created with the <title> tag as JSP Page and <body> tag as Hello World!.

Now change the text Hello World as Welcome to Java Login App.

Now under folder Web Pages open the folder WEB-INF and open web.xml. Under web.xml provide the text as given below:

<welcome-file-list>

<welcome-file>Login.jsp</welcome-file>

</welcome-file-list>

Ensure this tag is added inside the main tag <web-app> … </web-app>

Now back to the project and use the command Clean and Build and then Run. You will notice the application runs and the browser displays the application Login page as below. This ensures that the required JSP page is displayed on the application startup.

Now add the given HTML code inside the JSP page Login.jsp

<HTML>

<HEAD>

<META HTTP-EQUIV=”CONTENT-TYPE” CONTENT=”text/html; charset=windows-1252">

<TITLE>Login Application</TITLE>

</HEAD>

<BODY>

<H1>Welcome to Java Web Application for Login</H1>

<FORM NAME=”loginForm” ACTION=”loginServlet”>

<TABLE WIDTH=332 BORDER=0 CELLPADDING=4 CELLSPACING=0>

<COL WIDTH=135>

<COL WIDTH=181>

<TR VALIGN=TOP>

<TD WIDTH=135>

<P ALIGN=LEFT><FONT SIZE=3><B>Username</B></FONT></P>

</TD>

<TD WIDTH=181>

<P ALIGN=LEFT>

<INPUT TYPE=”text” NAME=”un”/>

</P>

</TD>

</TR>

<TR VALIGN=TOP>

<TD WIDTH=135>

<P ALIGN=LEFT><FONT SIZE=3><B>Password</B></FONT></P>

</TD>

<TD WIDTH=181>

<P ALIGN=LEFT>

<INPUT TYPE=”password” NAME=”pw”/>

</P>

</TD>

</TR>

<TR VALIGN=TOP>

<TD WIDTH=135>

<P ALIGN=LEFT>

</P>

</TD>

<TD WIDTH=181>

<INPUT TYPE=”submit” VALUE=”submit”>

</TD>

</TR>

</TABLE>

<BR>

<BR>

<TABLE WIDTH=100% BORDER=0 CELLPADDING=4 CELLSPACING=0>

<TR VALIGN=TOP>

<TD WIDTH=50%>

<P ALIGN=LEFT><FONT SIZE=6 STYLE=”font-size: 16pt”>This Java Web application demonstrates the user Login feature in the simplest form. This application utilises JDBC connection to MySQL Database. Java Servlet and Java Server Pages used along with core Java programming.</FONT></P>

</TD>

</TR>

</TABLE>

</FORM>

</BODY>

</HTML>

Now test the application with new JSP code by Clean and Build and then execute Run on the project LoginApp-1.0. This will display the Login page on the browser as shown below.

Now add two more JSP files under the folder Web Pages:

File Name : Login.jsp

<%@page contentType=”text/html” pageEncoding=”UTF-8"%>

<!DOCTYPE html>

<HTML>

<HEAD>

<META HTTP-EQUIV=”CONTENT-TYPE” CONTENT=”text/html; charset=windows-1252">

<TITLE>Login Application</TITLE>

</HEAD>

<BODY>

<H1>Welcome to Java Web Application for Login</H1>

<FORM NAME=”loginForm” ACTION=”loginServlet”>

<TABLE WIDTH=332 BORDER=0 CELLPADDING=4 CELLSPACING=0>

<COL WIDTH=135>

<COL WIDTH=181>

<TR VALIGN=TOP>

<TD WIDTH=135>

<P ALIGN=LEFT><FONT SIZE=3><B>User Name</B></FONT></P>

</TD>

<TD WIDTH=181>

<P ALIGN=LEFT>

<INPUT TYPE=”text” NAME=”un”/>

</P>

</TD>

</TR>

<TR VALIGN=TOP>

<TD WIDTH=135>

<P ALIGN=LEFT><FONT SIZE=3><B>Password</B></FONT></P>

</TD>

<TD WIDTH=181>

<P ALIGN=LEFT>

<INPUT TYPE=”password” NAME=”pw”/>

</P>

</TD>

</TR>

<TR VALIGN=TOP>

<TD WIDTH=135>

<P ALIGN=LEFT>

</P>

</TD>

<TD WIDTH=181>

<INPUT TYPE=”submit” VALUE=”submit”>

</TD>

</TR>

</TABLE>

<BR>

<BR>

<TABLE WIDTH=100% BORDER=0 CELLPADDING=4 CELLSPACING=0>

<TR VALIGN=TOP>

<TD WIDTH=50%>

<P ALIGN=LEFT><FONT SIZE=6 STYLE=”font-size: 16pt”>This Java Web application demonstrate the user Login feature in the simplest form. This application utilize JDBC connection to MySQL Database. Java Servlet and Java Server Pages used along with core Java programming.</FONT></P>

</TD>

</TR>

</TABLE>

</FORM>

</BODY>

</HTML>

File Name : Error.jsp

<%@page contentType=”text/html” pageEncoding=”UTF-8"%>

<!DOCTYPE html>

<HTML>

<HEAD>

<META HTTP-EQUIV=”CONTENT-TYPE” CONTENT=”text/html; charset=windows-1252">

<TITLE>Login Application</TITLE>

</HEAD>

<BODY LANG=”en-US” DIR=”LTR”>

<H1>Login Failure!!!</H1>

</BODY>

</HTML>

Now we need to incorporate a Servlet to submit the user credentials to the Java application. This will require adding a servlet.

Notice the given code in the Login.jsp where the ACTION is mentioned as loginServlet. Hence need to create the Servlet loginServlet in the application.

<FORM NAME=”loginForm” ACTION=”loginServlet”>

Inside the Source Packages folder create another folder Servlets.Now inside the folder Servlets create a new Servlet file with name loginServlet as shown in the image below.

Click Next and in the Configure Servlet Deployment screen do not forget to check Add information to deployment descriptor (web.xml). If you skip this check then you will have to add the servlet manually in the web.xml.

Click Finish and notice a servlet file loginServlet.java is created inside the Servlets folder. Open file web.xml inside folder WEB-INF and notice the below tag added in the file.

<servlet>

<servlet-name>loginServlet</servlet-name>

<servlet-class>Servlets.loginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>loginServlet</servlet-name>

<url-pattern>/loginServlet</url-pattern>

</servlet-mapping>

Now test the call received by loginServlet.java:

Re-execute the project using Clean and Build and then Run. Always stop the Apache Tomcat server before writing any code in the project.

You will notice the browser page displayed as shown above. Notice in the address bar the servlet name and the parameters for username and password passed to the servlet.

This indicates the servlet getting the submit call from the JSP.

Creating Java Source Classes:

Create the folder structure as given below:

Source Packages

↳ DataAccess

↳ Entity

↳ Servlets

Inside the folder Entity create the Java class UserBean.java with the code as below:

package Entity;

public class UserBean {

private Double id;

private String username;

private String password;

public void setId(Double id) {

this.id = id;

}

public void setUsername(String username) {

this.username = username;

}

public void setPassword(String password) {

this.password = password;

}

public Double getId() {

return id;

}

public String getUsername() {

return username;

}

public String getPassword() {

return password;

}

}

Inside the folder DataAccess create the Java class UserDAO.java with the code as below:

package DataAccess;

import Entity.UserBean;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

/**

*

* @author hiyas

*/

public class UserDAO {

public Boolean userLogin(UserBean bean) {

String Query = “”;

String username = “”;

String password = “”;

Boolean userFound = false;

Statement st = null;

Connection con = null;

ResultSet rs = null;

username = bean.getUsername();

password = bean.getPassword();

try {

Class.forName(“com.mysql.cj.jdbc.Driver”);

con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/devsprintdb”,”root”,”Hiya.S8!”);

if (con != null) {

st = con.createStatement();

} else {

System.out.println(“CLASS:UserDAO METHOD:userLogin MESSAGE: Connection is not initialized!”);

}

Query = “SELECT * FROM users WHERE USERNAME = ‘“ + username + “‘ AND PASSWORD = ‘“ + password + “‘“;

if (st != null) {

rs = st.executeQuery(Query);

} else {

System.out.println(“CLASS:UserDAO METHOD:userLogin MESSAGE: Resultset is not initialized!”);

}

if (rs.next()) {

System.out.println(“CLASS:UserDAO METHOD:userLogin MESSAGE: User Found : “ + username);

userFound = true;

} else {

System.out.println(“CLASS:UserDAO METHOD:userLogin MESSAGE: User not Found!”);

}

}catch(ClassNotFoundException | SQLException e){

System.out.println(“Exception : “ + e);

}

return userFound;

}

}

Inside the loginServlet.java enter code as below.

package Servlets;

import java.io.IOException;

import jakarta.servlet.ServletException;

import jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;

import Entity.UserBean;

import DataAccess.UserDAO;

/**

*

* @author hiyas

*/

public class loginServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

UserBean user = new UserBean();

UserDAO userDAO = new UserDAO();

String username = “”;

String password = “”;

Boolean userFound = false;

username = request.getParameter(“un”);

password = request.getParameter(“pw”);

user.setUsername(username);

user.setPassword(password);

userFound = userDAO.userLogin(user);

if(userFound == true){

response.sendRedirect(“Dashboard.jsp”);

System.out.println(“CLASS:loginServlet METHOD:processRequest MESSAGE: User Found : “ + username);

} else {

response.sendRedirect(“Error.jsp”);

System.out.println(“CLASS:loginServlet METHOD:processRequest MESSAGE: User Not Found : “ + username);

}

}

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

@Override

public String getServletInfo() {

return “Short description”;

}

}

Complete your MySQL setup:

Create database with name devsprintdb:

CREATE DATABASE `devsprintdb;

Create table with name users:

CREATE TABLE `users` (

`ID` double NOT NULL AUTO_INCREMENT,

`USERNAME` varchar(50) DEFAULT NULL,

`PASSWORD` varchar(100) DEFAULT NULL,

PRIMARY KEY (`ID`)

) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

INSERT INTO `devsprintdb`.`users`

(`USERNAME`,

`PASSWORD`)

VALUES

(<{USERNAME: }>,

<{PASSWORD: }>);

Connect MySQL Database in Netbeans:

Select Services tab in the left pane and right click on Databases → New Connection.

Under Driver dropdown select MySQL (Connector/J driver)

Using Add.. button locate the driver file mysql-connector-j-9.1.0.jar (you need to download this file if not available)

Click Next and a new database connection is created.

Execute the Application:

Clean and Build the project and then use Run command

The new browser window will display the page as below:

If you enter the correct user name and password the login success message will be displayed as below:

If your user name and/or password is incorrect then the error message will be displayed as below:

Conclusion:

In your project the files that are very important are given below. Ensure these file have the code as below.

Fine Name: web.xml

<web-app version=”6.0" xmlns=”https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=”https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd">

<servlet>

<servlet-name>loginServlet</servlet-name>

<servlet-class>Servlets.loginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>loginServlet</servlet-name>

<url-pattern>/loginServlet</url-pattern>

</servlet-mapping>

<session-config>

<session-timeout>

30

</session-timeout>

</session-config>

<welcome-file-list>

<welcome-file>Login.jsp</welcome-file>

</welcome-file-list>

</web-app>

File Name: pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0" xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.mycompany</groupId>

<artifactId>LoginApp</artifactId>

<version>1.0</version>

<packaging>war</packaging>

<name>LoginApp-1.0</name>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<jakartaee>11.0.0-M1</jakartaee>

</properties>

<dependencies>

<dependency>

<groupId>jakarta.platform</groupId>

<artifactId>jakarta.jakartaee-api</artifactId>

<version>${jakartaee}</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.32</version>

<scope>runtime</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.12.1</version>

<configuration>

<source>17</source>

<target>17</target>

</configuration>

</plugin>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-war-plugin</artifactId>

<version>3.4.0</version>

</plugin>

</plugins>

</build>

</project>

Comments

Post a Comment

Popular posts from this blog

Building a Seamless User Registration and Login Workflow in a Java Web Application