Back to Java
2026-03-068 min read

HTML Layout (Java)

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

Why This Matters

Java is a powerful programming language used in creating robust web applications. One of the essential aspects of web development is handling HTML layouts, which can be effectively managed using Java. In this tutorial, we will delve into the intricacies of using Java to manipulate HTML layouts, focusing on practical scenarios that are relevant to exams, interviews, and real-world development.

Understanding how to use Java for HTML layout management is crucial as it allows developers to create dynamic web pages with greater control and flexibility. This knowledge can be particularly valuable in building complex web applications where the ability to generate and manipulate HTML content on the fly is essential.

Prerequisites

Before diving into the core concept, it is essential to have a solid understanding of:

  1. Basic Java syntax and control structures (loops, conditionals)
  2. Understanding of Object-Oriented Programming (OOP) concepts in Java
  3. Familiarity with HTML and CSS basics
  4. Knowledge of the HTTP protocol and how it works
  5. Understanding of the Servlet API and its key interfaces and classes

Core Concept

Java provides several APIs to interact with HTML layouts, the most popular being JSP (JavaServer Pages) and Servlets. In this tutorial, we will focus on using Servlets for simplicity and better understanding.

A Servlet is a Java class that runs on a web server and handles HTTP requests from clients. To create a simple Servlet that generates HTML content, follow these steps:

  1. Create a new Java project in your favorite IDE (e.g., Eclipse or IntelliJ).
  2. Add the Servlet API library to your project's build path.
  3. Create a new package named webapp and inside it, create another package called servlet.
  4. Inside the servlet package, create a new Java class named LayoutServlet.
  5. Implement the javax.servlet.http.HttpServlet interface in your LayoutServlet class.
  6. Override the doGet() method to generate and send HTML content.

Here's an example of a simple Servlet that generates a basic HTML page:

package webapp.servlet;

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

public class LayoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang='en'>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("<title>My First Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Welcome to My First Servlet!</h1>");
out.println("</body>");
out.println("</html>");
}
}

To test the Servlet, deploy it on a web server (e.g., Apache Tomcat) and access it through a browser using the following URL format: http://localhost:8080/context-name/servlet-name.

Generating Dynamic HTML Content

To generate dynamic HTML content based on user input, you can use request parameters or session attributes. Here's an example of a Servlet that generates an HTML page with the current date and time:

package webapp.servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DynamicContentServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang='en'>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("<title>Dynamic Content</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Current Date and Time:</h1>");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = formatter.format(new Date());
out.println("<p>" + currentTime + "</p>");
out.println("</body>");
out.println("</html>");
}
}

Worked Example

Let's create a more complex example where we accept user input and generate an HTML table based on that input.

  1. Create a new Java class named TableServlet in the webapp.servlet package.
  2. Implement the javax.servlet.http.HttpServlet interface.
  3. Override the doGet() method to accept user input and generate an HTML table based on that input.

Here's an example of a Servlet that generates an HTML table with user-provided data:

package webapp.servlet;

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

public class TableServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String[] data = request.getParameterValues("data");
if (data != null && data.length > 0) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang='en'>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("<title>HTML Table Generator</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Your Data:</h1>");
out.println("<table border='1'>");
for (String row : data) {
out.println("<tr>");
String[] cells = row.split(",");
for (String cell : cells) {
out.println("<td>" + cell + "</td>");
}
out.println("</tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
} else {
response.sendRedirect("/"); // Redirect to the main page if no data is provided
}
}
}

To test the Servlet, create an HTML form that sends data to this Servlet and deploy both on a web server. Access the form URL (e.g., http://localhost:8080/context-name/table) and input some data separated by commas to see the generated table.

Generating Dynamic Tables with User Input

To create a dynamic table based on user input, you can modify the Servlet to accept request parameters for table headers and rows. Here's an example:

package webapp.servlet;

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

public class DynamicTableServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String headers = request.getParameter("headers");
String rows = request.getParameter("rows");

if (headers != null && rows != null) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang='en'>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("<title>Dynamic Table</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Your Data:</h1>");
out.println("<table border='1'>");
String[] headersArray = headers.split(",");
String[] rowsArray = rows.split("\n");
out.println("<thead>");
out.println("<tr>");
for (String header : headersArray) {
out.println("<th>" + header + "</th>");
}
out.println("</tr>");
out.println("</thead>");
out.println("<tbody>");
for (String row : rowsArray) {
String[] cells = row.split(",");
out.println("<tr>");
for (String cell : cells) {
out.println("<td>" + cell + "</td>");
}
out.println("</tr>");
}
out.println("</tbody>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
} else {
response.sendRedirect("/"); // Redirect to the main page if no data is provided
}
}
}

In this example, the Servlet accepts request parameters headers and rows, which contain comma-separated lists of table headers and rows, respectively. The HTML table is generated based on these inputs.

Common Mistakes

  1. Forgetting to set the content type: Always remember to set the response content type to "text/html" in your Servlet's doGet() method.
  2. Not handling null or empty input: Ensure that your Servlet can handle cases where the user does not provide any data or provides invalid data.
  3. Ignoring HTML escaping: Be aware of potential security risks when generating HTML content and use appropriate techniques to escape special characters (e.g., using `` in JSP).
  4. Not closing output streams: Always close the output stream after generating HTML content to avoid memory leaks.
  5. Overlooking Servlet lifecycle: Understand the Servlet lifecycle and how it affects your code execution (e.g., multiple requests handling, session management).
  6. Using deprecated APIs or methods: Familiarize yourself with the latest Servlet API documentation to avoid using outdated or deprecated classes and methods.
  7. Not optimizing performance: Consider optimizing your Servlets for better performance by minimizing memory usage, reducing response times, and implementing caching strategies.

Common Mistakes - Subheadings

  1. Forgetting to set the content type
  • Always remember to set the response content type to "text/html" in your Servlet's doGet() method.
  1. Not handling null or empty input
  • Ensure that your Servlet can handle cases where the user does not provide any data or provides invalid data.
  1. Ignoring HTML escaping
  • Be aware of potential security risks when generating HTML content and use appropriate techniques to escape special characters (e.g., using `` in JSP).
  1. Not closing output streams
  • Always close the output stream after generating HTML content to avoid memory leaks.
  1. Overlooking Servlet lifecycle
  • Understand the Servlet lifecycle and how it affects your code execution (e.g., multiple requests handling, session management).
  1. Using deprecated APIs or methods
  • Familiarize yourself with the latest Servlet API documentation to avoid using outdated or deprecated classes and methods.
  1. Not optimizing performance
  • Consider optimizing your Servlets for better performance by minimizing memory usage, reducing response times, and implementing caching strategies.

Practice Questions

  1. Create a Servlet that generates an HTML form for user input and sends the data to another Servlet for processing.
  2. Implement a Servlet that dynamically generates an HTML page based on user preferences (e.g., theme, language).
  3. Write a Servlet that accepts a CSV file as a request parameter and generates an HTML table from the contents of the file.
  4. Create a Servlet that allows users to upload an image and displays it in an HTML page.
  5. Implement a Servlet that generates a dynamic chart based on user-provided data (e.g., bar chart, pie chart).
  6. Write a Servlet that implements basic form validation (e.g., email address, password strength) before submitting the form to another Servlet for processing.
  7. Create a Servlet that generates an HTML page with a search box and displays search results based on user input.
  8. Implement a Servlet that allows users to create, edit, and delete records in a database using an HTML interface.

FAQ

  1. What is the difference between JSP and Servlets?
  • JSP (JavaServer Pages) is a technology for creating dynamic web pages using Java code embedded within HTML.
  • Servlets are Java classes that run on a web server and handle HTTP requests from clients, providing more control and flexibility compared to JSP.
HTML Layout (Java) | Java | XQA Learn