Back to Java
2025-12-297 min read

Pricing Table (Java)

Learn Pricing Table (Java) step by step with clear examples and exercises.

Why This Matters

Understanding how to create a pricing table using Java can significantly enhance your web development skills. Pricing tables are essential for displaying product or service prices in an organized and visually appealing manner, making it easier for users to compare different options and make informed decisions. In this lesson, we will not only learn how to create a responsive pricing table using HTML and CSS but also delve into the Java backend for handling data and dynamic content updates.

Prerequisites

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

  1. HTML: Hypertext Markup Language is used to structure content on the web.
  2. CSS: Cascading Style Sheets are used to style HTML elements and create layouts.
  3. Java: A high-level programming language for building robust, scalable applications.
  4. Java Servlets: Java Servlets are a platform for developing small, reusable components that run on a web server.
  5. Familiarity with databases (e.g., MySQL) and SQL is also beneficial but not strictly required.

Core Concept

HTML Structure

Let's start by creating the basic HTML structure for our pricing table:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pricing Table</title>
<!-- Link to an external CSS file -->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Our Pricing Plans</h1>
<!-- The pricing table container -->
<div id="pricing-table"></div>
</body>
</html>

In this example, we've created a simple HTML structure with a title and a `` for the pricing table. We'll link an external CSS file to style our table later.

Java Servlet

Next, let's create a Java servlet that fetches pricing data from a database and sends it to the client as JSON. For this example, we will use an in-memory data structure instead of a database.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.*;

public class PricingServlet extends HttpServlet {
private List<Map<String, Double>> prices = new ArrayList<>();

public void init() throws ServletException {
// Initialize pricing data (replace with actual data fetched from a database)
Map<String, Double> basicPlan = new HashMap<>();
basicPlan.put("name", "Basic");
basicPlan.put("price", 9.99);
basicPlan.put("features", Arrays.asList("1 GB storage", "10 emails per day"));
prices.add(basicPlan);

Map<String, Double> standardPlan = new HashMap<>();
standardPlan.put("name", "Standard");
standardPlan.put("price", 19.99);
standardPlan.put("features", Arrays.asList("5 GB storage", "50 emails per day"));
prices.add(standardPlan);

Map<String, Double> premiumPlan = new HashMap<>();
premiumPlan.put("name", "Premium");
premiumPlan.put("price", 29.99);
premiumPlan.put("features", Arrays.asList("10 GB storage", "100 emails per day"));
prices.add(premiumPlan);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Convert the list to JSON and send it as a response
JSONArray json = new JSONArray(prices);
PrintWriter out = response.getWriter();
out.print(json.toString());
}
}

In this example, we've created a simple servlet that returns pricing data in JSON format. We initialize the pricing data within the init() method, but you can replace this with actual data fetched from a database or an API.

Styling the Pricing Table (CSS)

Now let's style our pricing table using CSS:

body {
font-family: Arial, sans-serif;
}

#pricing-table {
width: 100%;
max-width: 800px;
margin: auto;
display: flex;
flex-wrap: wrap;
}

#pricing-table .plan {
width: calc(33.333% - 20px);
padding: 20px;
border: 1px solid #ccc;
box-sizing: border-box;
text-align: center;
}

#pricing-table .plan h3 {
margin: 0;
}

#pricing-table .features {
list-style-type: none;
padding: 0;
margin: 10px 0;
}

In this example, we've defined the basic layout for our pricing table and styled each plan with a border and some default styling. You can customize these styles to match your desired look and feel.

Combining Frontend and Backend

Finally, let's combine our frontend HTML and CSS with the backend Java servlet:

  1. Save the HTML and CSS code in separate files (e.g., index.html and styles.css).
  2. Create a new folder named WEB-INF inside your project directory.
  3. Inside the WEB-INF folder, create another folder called classes.
  4. Save the Java servlet code in a file named PricingServlet.java inside the classes folder.
  5. Create a new file named web.xml inside the WEB-INF folder and add the following content:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<description>Pricing Servlet</description>
<display-name>Pricing Servlet</display-name>
<servlet-name>PricingServlet</servlet-name>
<servlet-class>com.example.PricingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PricingServlet</servlet-name>
<url-pattern>/pricing</url-pattern>
</servlet-mapping>
</web-app>

Replace com.example with your package name if you've used one.

Now, when you run your Java servlet on a web server, it will serve the HTML and CSS files along with the pricing data in JSON format.

Worked Example

To see this example in action, follow these steps:

  1. Create a new Java project using your preferred IDE (e.g., IntelliJ IDEA or Eclipse).
  2. Follow the instructions above to create the HTML, CSS, and Java servlet files.
  3. Deploy your Java project on a web server that supports servlets (e.g., Apache Tomcat).
  4. Open your browser and navigate to the URL where your servlet is running (e.g., http://localhost:8080/pricing). You should see a responsive pricing table with the hardcoded data we provided earlier.

Common Mistakes

  1. Incorrect HTML structure: Make sure you've created the proper HTML structure for your pricing table, as shown in the Core Concept section.
  2. Mismatched CSS selectors: Ensure that your CSS selectors match the actual HTML elements on the page.
  3. Incorrect servlet mapping: Double-check that you've correctly mapped your servlet to the correct URL pattern in the web.xml file.
  4. Java compilation errors: Make sure there are no syntax or semantic errors in your Java code, and that you've compiled it successfully before running the application.
  5. Incorrect data fetching: If you're using an API or database to fetch pricing data, ensure that the data is being fetched correctly and that any potential errors are handled gracefully.
  6. Inconsistent styling: Ensure that your CSS styles are applied consistently across all HTML elements in the pricing table.
  7. Lack of responsiveness: Check that your pricing table remains responsive on different screen sizes by adjusting the max-width and other layout properties as needed.
  8. Missing or incorrect data: Verify that the pricing data being fetched from the database or API is accurate and complete, and handle any potential errors or missing data gracefully.

Practice Questions

  1. Modify the example to include a fourth pricing plan called "Ultimate" with 20 GB storage and unlimited emails per day.
  2. Style the pricing table to have rounded corners on each plan box.
  3. Add an option for users to sort the plans by price or features.
  4. Implement error handling in your Java servlet if the database query fails or returns no results.
  5. Create a form to allow users to create their own pricing plans and save them to a database.
  6. Extend this example to include additional features, such as a trial period, discounts, or customizable options for each plan.
  7. Investigate using AJAX to update the pricing table dynamically without requiring a full page refresh.
  8. Explore using a front-end JavaScript framework like React or Angular to create a more interactive and dynamic pricing table.

FAQ

  1. Why is my pricing table not responsive? Ensure that you've set the max-width property on the pricing table container, and that the plan boxes have flexible widths using percentages or calc().
  2. How do I handle errors in my Java servlet? You can use try-catch blocks to catch exceptions and return error messages to the client.
  3. Why is my CSS not being applied to the pricing table? Check that your CSS file is correctly linked in the HTML file, and that there are no syntax errors in your CSS code.
  4. How do I sort the pricing plans by price or features? You can use JavaScript to sort the data on the client-side based on the selected option. Alternatively, you can send the sorted data from the servlet to the client and apply the sorting on the HTML side.
  5. Why is my form not saving new pricing plans to the database? Ensure that your database connection is working correctly, and that there are no syntax errors in your SQL queries. Make sure that you've implemented error handling for potential issues like missing data or duplicate entries.
  6. How can I make my pricing table more visually appealing? Experiment with different color schemes, fonts, and animations to create a unique and engaging user experience.
  7. What other features can I add to my pricing table? Consider adding additional options like customizable plans, trial periods, or discounts for long-term subscriptions. You could also incorporate testimonials, customer reviews, or trust badges to build credibility and encourage conversions.
Pricing Table (Java) | Java | XQA Learn