How do I create a Hello World Applet?

The code below demonstrate the very basic of Java applet. Applet is a small Java application that can be embedded on the web browser.

package org.kodejava.example.applet;

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {
    public void init() {

    public void start() {

    public void stop() {

    public void destroy() {

    public void paint(Graphics g) {
        g.drawString("Hello World", 50, 100);

To display the applet we need to create an HTML document. Here is a simple example of the document.

    <title>Hello World Applet</title>


You can now load the applet in your browser or by using the appletviewer utility.

How do I create a HelloWorld Servlet?

Servlet is a Java solution for creating a dynamic web application, it can be compared with the old CGI technology. Using Servlet we can create a web application that can display information from database, receive information from a web form to be stored on the application database.

This example show the very basic of servlet, it returns a hello world html document for the browser. At the very minimum a servlet will have a doPost() and doGet() method which handles the HTTP POST and GET request.

package org.kodejava.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

    public HelloWorld() {

    protected void doGet(HttpServletRequest req, HttpServletResponse res) 
            throws ServletException, IOException {
        doPost(req, res);

    protected void doPost(HttpServletRequest req, HttpServletResponse res) 
            throws ServletException, IOException {

        PrintWriter writer = res.getWriter();
        writer.println("<head><title>Hello World Servlet</title></head>");
        writer.println("<body>Hello World! How are you doing?</body>");

For a servlet to works on a servlet container such as Apache Tomcat we need to add or register the servlet in the application’s web.xml file. This configuration tells the container about our servlet class and a url that maps a request to the servlet.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"

When the servlet is deployed to the container we can access it from a url in a form of http://localhost:8080/app-name/HelloWorld.