In this blog, I will guide you through creating a Roll Dice Java-based web application. We will use Java 17+, Maven, and Apache Tomcat to build, configure, and deploy the application. This web application will generate a random number between 1 and 6 when a button is clicked, simulating a dice roll. This is an exciting and practical example that helps in learning about servlets, JSPs, Maven build, and deploying with Tomcat.

Prerequisites

Make sure you have the following installed on your system:

  1. Java 17+ (JDK 17 or newer) – For compiling and running the Java code.
  2. Maven (Latest Version) – For managing dependencies and building the project.
  3. Apache Tomcat (9.x or newer) – For deploying and running the web application.
  4. An IDE – Like IntelliJ IDEA, Eclipse, or VS Code for easier development.

Let’s get started!

Step 1: Set Up the Maven Project

We will create a new Maven web application using a Maven archetype to simplify the initial setup.

Command

mvn archetype:generate -DgroupId=com.example -DartifactId=rolldice-webapp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Explanation

  • -DgroupId=com.example: Defines the project’s group identifier, typically the reversed domain name.
  • -DartifactId=rolldice-webapp: Names the project.
  • -DarchetypeArtifactId=maven-archetype-webapp: Uses a pre-defined Maven archetype for web applications.

This will create a new project called rolldice-webapp with a default folder structure.

Step 2: Understand the Project Structure

The project will have the following structure:

rolldice-webapp/
├── pom.xml
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── RollDiceServlet.java
│   │   ├── webapp/
│   │   │   ├── WEB-INF/
│   │   │   │   └── web.xml
│   │   │   └── index.jsp
  • pom.xml: Manages dependencies and project configuration.
  • src/main/java: Holds Java source files.
  • src/main/webapp: Contains web resources (JSP files, etc.).

Step 3: Update pom.xml for Dependencies

Modify pom.xml to ensure compatibility with Java 17 and to add the necessary dependencies.

Updated pom.xml Content

<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>rolldice-webapp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- Servlet API -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>
        </plugins>
    </build>
</project>

Step 4: Create the RollDiceServlet Java Class

Create a new Java class named RollDiceServlet in the directory src/main/java/com/example/.

RollDiceServlet.java Content

package com.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

@WebServlet("/roll")
public class RollDiceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        int rollResult = random.nextInt(6) + 1;

        response.setContentType("text/html");
        response.getWriter().write("<h1>Dice Roll Result: " + rollResult + "</h1>");
    }
}

Explanation

  • @WebServlet("/roll"): Maps this servlet to the /roll URL.
  • doGet() Method: Generates a random number between 1 and 6 to simulate a dice roll.

Step 5: Create index.jsp

Add a JSP file named index.jsp to the directory src/main/webapp/. This will serve as the landing page of the application.

index.jsp Content

<!DOCTYPE html>
<html>
<head>
    <title>Roll Dice Application</title>
</head>
<body>
    <h1>Welcome to the Roll Dice Web Application!</h1>
    <p><a href="roll">Click here to roll the dice</a></p>
</body>
</html>

Explanation

  • Link to /roll: This link directs the user to the /roll URL, which triggers the servlet to roll the dice and display the result.

Step 6: Build the Application

To build the application, run the following Maven command in the terminal:

Command

mvn clean package

Explanation

  • mvn clean: Deletes the target directory to clean any old build files.
  • mvn package: Compiles the code and packages it as a WAR file (rolldice-webapp-1.0-SNAPSHOT.war).

Step 7: Deploy to Tomcat

Deploy the generated WAR file to Tomcat to run the web application.

  1. Copy the WAR File to Tomcat cp target/rolldice-webapp-1.0-SNAPSHOT.war <TOMCAT_HOME>/webapps/
  2. Restart Tomcat <TOMCAT_HOME>/bin/shutdown.sh <TOMCAT_HOME>/bin/startup.sh

Explanation

  • Deploy WAR: Copying the WAR file into Tomcat’s webapps folder deploys it automatically.
  • Restart Tomcat: Ensures the application is loaded properly.

Accessing the Application

Once the WAR file has been deployed, open your browser and access the following URLs:

  1. Index Page http://localhost:8080/rolldice-webapp/index.jsp
    • This page provides a link to roll the dice.
  2. Roll Dice Servlet http://localhost:8080/rolldice-webapp/roll
    • This URL invokes the servlet, which generates and displays a random number between 1 and 6.

Conclusion

Congratulations! You have successfully created and deployed a Roll Dice Java-based web application using Maven and Tomcat. You learned how to generate a new project with Maven, create a servlet, build a WAR file, and deploy it to Tomcat. This simple project demonstrates the fundamentals of servlets and JSPs while also offering an engaging, interactive example.

Feel free to extend this project with additional features, such as allowing users to roll multiple dice or integrating with a database to keep track of previous results.

Any queries pls contact us @Rushi-InfoTech

Happy coding! 🎲🚀

Similar Posts

Leave a Reply

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