Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC with MySQL - Sample Project For Calculating Electricity Bill

To create a simple Spring MVC application that calculates an electricity bill using a MySQL database, follow this guide:

1. Maven Dependencies

Add the following dependencies to your pom.xml:

<!-- Spring Web MVC and JDBC -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.x.x.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.x.x.RELEASE</version>
</dependency>

<!-- MySQL Connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.x.x</version>
</dependency>

2. Database Setup

Create a table in MySQL:

CREATE TABLE electricity_bill (
    id INT AUTO_INCREMENT PRIMARY KEY,
    customer_name VARCHAR(50),
    units_consumed DOUBLE,
    total_bill DOUBLE
);

3. Spring MVC Configuration

Create a Spring configuration:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.demo")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/your_database_name");
        dataSource.setUsername("your_username");
        dataSource.setPassword("your_password");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    // Other configurations...
}

4. Model

public class ElectricityBill {
    private int id;
    private String customerName;
    private double unitsConsumed;
    private double totalBill;

    // getters, setters, constructors...
}

5. DAO Layer

@Repository
public class BillDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int saveBill(ElectricityBill bill) {
        String sql = "INSERT INTO electricity_bill (customer_name, units_consumed, total_bill) VALUES (?, ?, ?)";
        return jdbcTemplate.update(sql, bill.getCustomerName(), bill.getUnitsConsumed(), bill.getTotalBill());
    }
}

6. Service Layer

@Service
public class BillService {

    @Autowired
    private BillDAO billDAO;

    private static final double RATE_PER_UNIT = 5.0;  // Example rate

    public double calculateBill(double units) {
        return units * RATE_PER_UNIT;
    }

    public int saveBill(ElectricityBill bill) {
        double total = calculateBill(bill.getUnitsConsumed());
        bill.setTotalBill(total);
        return billDAO.saveBill(bill);
    }
}

7. Controller

@Controller
@RequestMapping("/bill")
public class BillController {

    @Autowired
    private BillService billService;

    @GetMapping("/calculate")
    public String showBillForm(Model model) {
        model.addAttribute("bill", new ElectricityBill());
        return "billForm";
    }

    @PostMapping("/calculate")
    public String calculateBill(@ModelAttribute("bill") ElectricityBill bill, Model model) {
        billService.saveBill(bill);
        model.addAttribute("bill", bill);
        return "billResult";
    }
}

8. Views

  • billForm.jsp:
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<form:form action="calculate" method="post" modelAttribute="bill">
    Customer Name: <form:input path="customerName"/>
    Units Consumed: <form:input path="unitsConsumed"/>
    <input type="submit" value="Calculate"/>
</form:form>
  • billResult.jsp:
<h2>Electricity Bill Result</h2>
<p>Customer: ${bill.customerName}</p>
<p>Units: ${bill.unitsConsumed}</p>
<p>Total Bill: ${bill.totalBill}</p>

Run the application and navigate to /bill/calculate to input the customer name and units consumed. The system will calculate and display the bill based on the predefined rate.

Adjustments may be necessary based on specific requirements and configurations.