Back to Java
2026-01-278 min read

HTML Events (Java)

Learn HTML Events (Java) step by step with clear examples and exercises.

Why This Matters

Java is a powerful programming language that plays a significant role in web development due to its robustness and versatility. One essential aspect of creating interactive web applications using Java is handling HTML events. By understanding how to handle these events effectively, you can create a more engaging and responsive user experience. This skill is highly sought after in the job market and is crucial for both beginners and experienced developers.

Prerequisites

To follow this guide, you should have a basic understanding of:

  1. Java programming language syntax and data types
  2. HTML and CSS basics, including creating web pages with forms and buttons
  3. Setting up a development environment for Java web applications, such as Apache Tomcat or Jetty
  4. Understanding the concept of Servlets and JSPs in Java web development
  5. Familiarity with JavaScript and its role in handling HTML events (optional but recommended)

Core Concept

Listening to HTML Events in Java

To handle events in an HTML document using Java, we use Servlets. In this guide, we will focus on using Servlets for simplicity.

First, create a new servlet that extends the javax.servlet.http.HttpServlet class:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Your event handling code goes here
}
}

Next, we need to listen for specific events in our HTML document. This is done by adding JavaScript code that sends an asynchronous HTTP request to the servlet whenever an event occurs. For example, to handle a click event on a button:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Java and HTML Events</title>
</head>
<body>
<button id="myButton">Click me!</button>
<!-- Your JavaScript code goes here -->
</body>
</html>

Add the following JavaScript code to handle the click event:

document.getElementById("myButton").addEventListener("click", function() {
// Send an HTTP request to your servlet when the button is clicked
fetch("/MyServlet");
});

Handling the Request in Java

Now, we can handle the request sent from our JavaScript code by modifying the doGet() method in our servlet:

public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the event data (if any) from the request
String data = request.getParameter("eventData");

// Process the event data as needed
if (data != null) {
System.out.println("Event data received: " + data);
}
}
}

In this example, we are simply printing the event data to the console. You can replace this with your own logic to handle the event appropriately.

Event Propagation and Bubbling

JavaScript events can propagate in two ways: capturing (from the root element to the target) and bubbling (from the target to the root). By default, event listeners capture events starting from the target element. However, you can also listen for events during the capturing phase using the addEventListener() method with the third argument set to true.

document.getElementById("myButton").addEventListener("click", function(event) {
// This event listener will fire before the default click handler on myButton
}, true);

Preventing Default Event Behavior

To prevent the default behavior of an event, such as a form submission or link navigation, you can call event.preventDefault() in your JavaScript code:

document.getElementById("myForm").addEventListener("submit", function(event) {
// Prevent the form from submitting and refresh the page
event.preventDefault();
});

Worked Example

Let's create a simple example where clicking a button changes the text of another element on the page.

  1. Create a new servlet called MyServlet as shown earlier.
  2. Modify the HTML document to include a button and a paragraph:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Java and HTML Events</title>
</head>
<body>
<button id="myButton">Click me!</button>
<p id="myParagraph">Initial text.</p>
<!-- Your JavaScript code goes here -->
</body>
</html>
  1. Add the following JavaScript code to handle the click event and update the paragraph's text:
let myParagraph = document.getElementById("myParagraph");

document.getElementById("myButton").addEventListener("click", function(event) {
// Prevent the default button click behavior (e.g., form submission if it's inside a form)
event.preventDefault();

// Send an HTTP request to your servlet when the button is clicked
fetch("/MyServlet?eventData=buttonClicked")
.then(response => response.text())
.then(data => {
myParagraph.innerText = data;
});
});
  1. Modify the doGet() method in MyServlet to return a new text for the paragraph:
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = request.getParameter("eventData");

if (data != null && data.equalsIgnoreCase("buttonClicked")) {
// Set the text for the paragraph in the HTML document
PrintWriter out = response.getWriter();
out.println("Button clicked!");
} else {
// Return an error message if the event data is not recognized
PrintWriter out = response.getWriter();
out.println("Unknown event data: " + data);
}
}
}

Now, when you run this example and click the button, the text in the paragraph should change to "Button clicked!".

Common Mistakes

  1. Forgetting to add the JavaScript event listener: Make sure to include the JavaScript code that adds an event listener to your HTML elements.
  2. Not handling the request correctly in Java: Ensure that you process the event data appropriately and return any necessary information back to the client.
  3. Incorrectly setting up the development environment: Double-check that you have the correct servlet container (e.g., Apache Tomcat) installed and configured correctly.
  4. Overlooking potential security issues: Be aware of potential security risks, such as Cross-Site Scripting (XSS), when handling user input in your Java code.
  5. Not testing thoroughly: Always test your application thoroughly to ensure that it works as expected and handles events correctly.
  6. Ignoring event propagation and bubbling: Understand how events propagate and use the appropriate event listener configuration to handle them effectively.
  7. Failing to prevent default event behavior when necessary: Prevent the default behavior of an event if you want to handle it yourself instead of allowing the browser's default behavior to occur.
  8. Not considering event cancellation: Be aware that some events can be cancelled by calling event.stopPropagation() or event.preventDefault().
  9. Forgetting to clean up resources: If your servlet maintains any resources (e.g., database connections), make sure to release them when the servlet is destroyed to avoid memory leaks.
  10. Not following best practices for writing secure and maintainable code: Always write clean, well-documented, and secure code that follows established best practices for Java web development.

Practice Questions

  1. Modify the example above so that clicking the button changes the background color of the paragraph instead of its text.
  2. Create a form with two input fields: one for a user's name and another for their email address. Write JavaScript code to send an HTTP request to your servlet when the form is submitted, passing the user's name and email as parameters. In the servlet, save the user's information in a database (you can use an in-memory data structure for simplicity).
  3. Create a Java servlet that listens for a mouse move event on a specific HTML element. When the event occurs, calculate the distance between the current mouse position and the center of the element and return this value to the client.
  4. Modify the example above so that clicking the button changes the text of another element based on a random number generated by the servlet.
  5. Create a Java servlet that listens for a key press event on a specific HTML input field. When the event occurs, calculate the ASCII value of the pressed key and return this value to the client.
  6. Write JavaScript code to create a custom event in response to a user's mouse hovering over an element for more than 5 seconds. Send this custom event to your servlet when it occurs, along with the hovered element's ID. In the servlet, save the timestamp and element ID associated with each custom event.
  7. Create a Java servlet that listens for a resize event on an HTML window or specific element. When the event occurs, calculate the new dimensions of the window/element and return this information to the client.
  8. Write JavaScript code to create a custom event in response to a user's scrolling past a specific point within an HTML document. Send this custom event to your servlet when it occurs, along with the scroll position and direction (up or down). In the servlet, save the timestamp and scroll data associated with each custom event.
  9. Modify the example above so that clicking the button sends a different HTTP request based on whether the Shift key is pressed while clicking the button.
  10. Create a Java servlet that listens for a touch event (e.g., tap, swipe) on an HTML element. When the event occurs, calculate the number of fingers involved in the event and return this value to the client.

FAQ

Q: Why can't I use JavaScript directly in my Java code?

A: JavaScript and Java are separate languages that run on different platforms. You need to use a bridge, such as AJAX requests or WebSockets, to communicate between them.

Q: Can I handle HTML events using JSP instead of Servlets?

A: Yes, you can handle HTML events in JSP using JavaScript and the `` tag. However, using Servlets provides more control over the request-response cycle and is generally preferred for handling events in Java web applications.

Q: How do I secure my Java servlet against potential security threats like XSS?

A: To mitigate XSS attacks, sanitize any user input before using it in your Java code or returning it to the client. You can also use Content Security Policy (CSP) headers to restrict the types of content that can be executed on your web page.

Q: Can I handle HTML events in a JavaFX application?

A: Yes, you can handle HTML events in a JavaFX application using WebView or WebEngine components. These allow you to embed an HTML document within your JavaFX application and interact with it programmatically.

Q: How do I test my Java servlet for handling HTML events?

A: To test your servlet, you can use a tool like Postman or curl to send HTTP requests to your servlet and verify the response. You can also create an HTML page that includes JavaScript code to simulate user interactions and test how your servlet handles them.

HTML Events (Java) | Java | XQA Learn