Skip to main content

Command Palette

Search for a command to run...

Creating JAVA WEB-APP

Published
2 min readView as Markdown

1. Create the Project

  • File → New → Project

  • Select Maven as the build system.

  • Check “Create from archetype”, then choose org.apache.maven.archetypes:maven-archetype-webapp. IntelliJ will fetch this standard archetype from Maven Central. JavaPointersMedium

  • Click Next, and provide GroupId, ArtifactId, JDK (Project SDK), and accept the default or your own Maven installation.

  • Finish to generate the project structure.

2. Add Java Source Folders

  • Right-click src/main/New → Directory, create java.

  • Do the same for test/java if needed.

  • Right-click the new java folder → Mark Directory As → Sources Root so IntelliJ picks it up properly.

4. Update pom.xml for WAR Packaging

Make sure your pom.xml includes:

  • <packaging>war</packaging>

  • The Servlet API dependency, e.g., from Jakarta (for newer Tomcat versions):

      <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.0.0</version>
        <scope>provided</scope>
      </dependency>
    
    • Optionally, configure Maven WAR plugin and disable requirement for web.xml.

(This aligns with the standard Maven setup you’d use in Path A.)

Step 5: Create a Servlet

  1. Inside src/main/java, create a package (e.g., com.example.web).

  2. Add a class extending HttpServlet:

package com.example.web;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Hello, Java Web App!</h1>");
    }
}

Step 6: Register the Servlet

Use Annotation (modern way)

Add this above your servlet class:

import jakarta.servlet.annotation.WebServlet;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    ...
}

Step 7: Add JSP or Static Pages (Optional)

Inside src/main/webapp, you can place JSPs or HTML files.
For example: index.jsp

<html>
  <body>
    <h2>Welcome to My Java Web App</h2>
    <a href="hello">Go to Servlet</a>
  </body>
</html>

Step 8: Build the WAR

Run in terminal:

mvn clean package

This creates a .war file under target/your-artifact-id.war.

Step 9: Deploy to Tomcat

  1. Copy the .war file into Tomcat’s webapps folder.
    Example:

     cp target/mywebapp.war /path/to/tomcat/webapps/
    
  2. Start Tomcat:

     ./catalina.sh run
    
  3. Visit in browser:

     http://localhost:8080/mywebapp/hello
    

✅ At this point, you have a running Java web app.