Simple Java Code to display Hello, World on the web

CK CK 3788 
Created at  
569 0 0

Introduction to Java Web Applications

To display "Hello, World" on the web using Java, you need to create a web application. This involves a server-side component written in Java that responds to HTTP requests from web browsers (clients). The standard for building web applications in Java is the Java Servlet API, which defines how Java programs interact with web servers.

Simple Java Code to display Hello, World on the web

Key components typically involved:

  • Client: A web browser (e.g., Chrome, Firefox) that sends HTTP requests.
  • Web Server / Servlet Container: Software like Apache Tomcat, Jetty, or WildFly that hosts the Java web application. It manages the application's lifecycle, processes incoming HTTP requests, and delegates them to the appropriate Java components (Servlets).
  • Java Servlet: A Java class that extends HttpServlet and implements methods to handle specific HTTP request types (e.g., GET, POST).

 

Core Component: Java Servlets

A Servlet is a Java class that extends the capabilities of servers that host web sites. While servlets can respond to any type of request, they are commonly used to extend web servers, providing a component-based, platform-independent method for building dynamic web applications.

For a simple "Hello, World" display, we typically implement the doGet() method of an HttpServlet. This method is invoked when a client sends an HTTP GET request to the servlet's configured URL. Inside this method, we obtain a PrintWriter object from the HttpServletResponse and use it to write the response (usually HTML) directly back to the client's browser.

 

Simple Hello World Servlet Code

Here's the minimal Java code for a servlet that displays "Hello, World":

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

// The @WebServlet annotation maps this servlet to the URL pattern "/hello"
// When a request comes to a URL ending with "/hello" within this application,
// this servlet will be invoked.
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    // This method is called when an HTTP GET request is made to this servlet.
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Set the content type of the response to HTML, indicating to the browser
        // how to interpret the response body.
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8"); // Ensure proper character encoding

        // Get a PrintWriter object to send the response back to the client.
        // This is where you write the actual content that the browser will display.
        PrintWriter out = response.getWriter();

        try {
            // Write the HTML content directly to the client's browser.
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Hello, World!</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Hello, World!</h1>");
            out.println("<p>This is a simple Java Servlet example.</p>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            // It's good practice to close the PrintWriter to release resources.
            out.close();
        }
    }
}

 

Explanation of Key Elements:

  • @WebServlet("/hello"): This annotation (available since Servlet API 3.0) maps this HelloServlet class to the URL path /hello. When a browser requests a URL like http://your-server/your-app-context/hello, this servlet will handle it.
  • extends HttpServlet: This makes our class a specialized Servlet capable of handling HTTP requests. HttpServlet provides convenient methods like doGet(), doPost(), etc.
  • doGet(HttpServletRequest request, HttpServletResponse response): This method is overridden to handle HTTP GET requests.
    • request: An object containing information about the client's request (e.g., headers, parameters, URL).
    • response: An object used to send data back to the client (e.g., setting content type, writing HTML).
  • response.setContentType("text/html"): This crucial line tells the client's browser that the content being sent back is HTML, so the browser should render it accordingly.
  • response.getWriter(): Returns a PrintWriter object, which is used to send text-based response data (like HTML) to the client.
  • out.println(...): These lines write the HTML content directly into the HTTP response body, which the browser then receives and displays.

 

Project Setup and Dependencies

To compile and run this servlet, you'll need a Java Development Kit (JDK) and typically a build automation tool like Maven or Gradle.

Maven pom.xml configuration (minimal):

<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.example</groupId>
    <artifactId>my-hello-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging> <!-- Crucial for web applications -->

    <properties>
        <maven.compiler.source>11</maven.compiler.source> <!-- Your JDK version -->
        <maven.compiler.target>11</maven.compiler.target> <!-- Your JDK version -->
        <jakarta.servlet.version>5.0.0</jakarta.servlet.version> <!-- For Servlet API 5.0+ -->
        <!-- Or for older Servlet API (3.x-4.x / Java EE) use:
        <javax.servlet.version>4.0.1</javax.servlet.version>
        -->
    </properties>

    <dependencies>
        <!-- Servlet API dependency -->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>${jakarta.servlet.version}</version>
            <scope>provided</scope> <!-- Provided by the servlet container (e.g., Tomcat) -->
        </dependency>
        <!-- For older Servlet API (3.x-4.x / Java EE):
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        -->
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName> <!-- Sets the WAR file name -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version> <!-- Ensure WAR plugin is used -->
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

The scope for the Servlet API dependency is set to provided. This means the Servlet Container (like Tomcat) will provide this library at runtime, so it doesn't need to be bundled within your .war file, keeping the deployment artifact smaller.

Typical Project Structure (for a Maven web application):

my-hello-app/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── example/
        │           └── HelloServlet.java  (Your servlet code goes here)
        └── webapp/                      (Contains web resources)
            └── WEB-INF/
                └── web.xml (Optional: if using annotations, this file might be empty or absent.
                             It's used for traditional servlet mappings or other configurations.)

 

Building and Deployment

1. Compile and Package: Use your chosen build tool (e.g., Maven) to compile the Java code and package it into a .war (Web Application Archive) file.

mvn clean package

This command will typically create a file named my-hello-app.war (based on in pom.xml) inside the target/ directory of your project.

2. Deploy to a Servlet Container: Copy the generated .war file (e.g., my-hello-app.war) into the webapps directory of your Servlet Container (e.g., Apache Tomcat, usually located at TOMCAT_HOME/webapps). Tomcat will automatically unpack and deploy the application.

3. Start the Server: Ensure your Tomcat server (or whichever container you are using) is running.

 

Accessing the Application

Once your application is deployed and the server is running, open your web browser and navigate to the following URL:

http://localhost:8080/my-hello-app/hello

  • localhost:8080: This is the default address and port for many local Tomcat installations. Your actual port might vary.
  • my-hello-app: This is the context path of your application. By default, Tomcat uses the name of the deployed .war file (without the .war extension) as the context path.
  • /hello: This is the specific URL pattern defined by the @WebServlet("/hello") annotation in your HelloServlet class.

You should then see a web page in your browser displaying "Hello, World!" as an heading.

 

Modern Simplification: Spring Boot

While Servlets are the foundational technology for Java web applications, modern development often leverages frameworks like Spring Boot to significantly simplify setup, configuration, and deployment. Spring Boot applications can be run as standalone executable JARs with an embedded web server (like Tomcat, Jetty, or Undertow), eliminating the need for separate .war files and manual server deployment.

 

Example with Spring Boot:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication // Marks this as a Spring Boot application entry point
@RestController      // Marks this class as a REST controller to handle incoming web requests
public class HelloWorldApplication {

    public static void main(String[] args) {
        // Starts the Spring application, including the embedded web server
        SpringApplication.run(HelloWorldApplication.class, args);
    }

    // Maps HTTP GET requests to the root path "/"
    @GetMapping("/")
    public String hello() {
        // Returns the string directly as the HTTP response body
        return "Hello, World!";
    }
}

 

To run this Spring Boot example:
1. Create a Maven or Gradle project and add the spring-boot-starter-web dependency.
2. Place the HelloWorldApplication.java file in your project.
3. Run the main method of HelloWorldApplication (e.g., from your IDE or via mvn spring-boot:run).
4. Open your web browser and navigate to http://localhost:8080/.

Spring Boot handles all the underlying Servlet API integration, web server setup, and configuration, allowing developers to focus solely on the application's business logic and endpoints.

Tags Apache Tomcat Gradle HTTP Request Hello World Java JDK Java Code Example Java Servlet Java Web Application Maven Maven Build Servlet API Spring Boot Web Development Facebook X
Comments 0
Similar posts
  1. Beyond venv: Java's Project Isolation Strategy
    486
  2. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    599
  3. Mastering Excel Data Importation in PHP
    558
  4. Equal Height Blocks in Bootstrap with JavaScript
    713
  5. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,078
  6. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    747
  7. Dynamic DNS Made Easy: Building a Python-Based Solution
    796
  8. CentOS 7 PHP Apache Kafka: Installation, Examples, and System Diagram
    311
  9. What Replaced JSP? Modern Java Web Dev Explained (with Examples)
    267
  1. Java Variant Type
    212
  2. Your Comprehensive Guide to Flink & Kafka for Real-time Stream Processing
    422
  3. Why Java Spring Framework is Considered Optimized for Docker
    1,031
  4. Spring Framework: Evolution, Trends, and Architectural Innovation
    1,275
  5. Java Kafka on CentOS 7: Install, Configure, & Run with Examples
    430
  6. Java Maps: HashMap vs. LinkedHashMap vs. TreeMap Explained
    234
  7. How to resize image ?
    1,314
  8. How to set and get sessions on JSP code ?
    1,041
  9. How to add a declaration on JSP code ?
    1,128
  10. How to include file in JSP ?
    1,256
  11. How to print out text strings on HTML directly ?
    909
  12. Clipboard copy function working
    3,381
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,208
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    208
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    268
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    354
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    203
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233