Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring MVC with MySQL - Sample Project For Calculating Electricity Bill
Next article icon

Spring MVC with MySQL - Sample Project For Calculating Electricity Bill

Last Updated : 31 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Let us see a sample electricity bill calculation project by using Spring MVC + MySQL connectivity + JDBCTemplate. Additionally, let us test the same by using MockMvc + JUnit.

MySQL Queries:

DROP DATABASE IF EXISTS test;    CREATE DATABASE test;    USE test;    DROP TABLE test.personsdetails;    CREATE TABLE personsdetails (    id int(6) unsigned NOT NULL,    Name varchar(50) NOT NULL,    serviceNumber varchar(10) NOT NULL,    consumedUnits int(11) NOT NULL,    gender varchar(10) DEFAULT NULL,    PRIMARY KEY (id)  ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;    INSERT INTO test. personsdetails  (id,Name, serviceNumber, consumedUnits,gender) VALUES  (1,'personA','123-456',250,'Female');    INSERT INTO test. personsdetails  (id,Name, serviceNumber, consumedUnits,gender) VALUES  (2,'personB','246-468',350,'male');    INSERT INTO test. personsdetails  (id,Name, serviceNumber, consumedUnits,gender) VALUES  (3,'personC','123-678',150,'Female');    INSERT INTO test. personsdetails  (id,Name, serviceNumber, consumedUnits,gender) VALUES  (4,'personD','246-789',220,'male');    INSERT INTO test. personsdetails  (id,Name, serviceNumber, consumedUnits,gender) VALUES  (5,'personE','146-189',500,'female');    SELECT * FROM test.personsdetails;

Output:

Spring MVC with MySQL Output
 

For this MySQL data, let us get the electricity charges by using Spring MVC + JdbcTemplate

Implementation

Project Structure:

Project Structure
 

Maven-driven project

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" x          mlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                              http://maven.apache.org/maven-v4_0_0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.persons</groupId>    <artifactId>SpringMVCElectricityBillCalculation</artifactId>    <packaging>war</packaging>    <properties>       <maven.compiler.source>1.8</maven.compiler.source>       <maven.compiler.target>1.8</maven.compiler.target>    </properties>    <version>0.0.1-SNAPSHOT</version>    <name>SpringMVCElectricityBillCalculation Maven Webapp</name>    <url>http://maven.apache.org</url>    <dependencies>       <dependency>          <groupId>junit</groupId>          <artifactId>junit</artifactId>          <version>4.12</version>          <scope>test</scope>       </dependency>       <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->       <dependency>          <groupId>org.mockito</groupId>          <artifactId>mockito-all</artifactId>          <version>1.9.5</version>          <scope>test</scope>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-webmvc</artifactId>          <version>5.1.1.RELEASE</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-context</artifactId>          <version>5.1.1.RELEASE</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-test</artifactId>          <version>5.1.1.RELEASE</version>          <scope>test</scope>       </dependency>       <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->       <dependency>          <groupId>org.apache.tomcat</groupId>          <artifactId>tomcat-jasper</artifactId>          <version>9.0.12</version>       </dependency>       <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->       <dependency>          <groupId>javax.servlet</groupId>          <artifactId>servlet-api</artifactId>          <version>3.0-alpha-1</version>       </dependency>       <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->       <dependency>          <groupId>javax.servlet</groupId>          <artifactId>jstl</artifactId>          <version>1.2</version>       </dependency>       <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->       <dependency>          <groupId>mysql</groupId>          <artifactId>mysql-connector-java</artifactId>          <version>8.0.11</version>       </dependency>       <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-jdbc</artifactId>          <version>5.1.1.RELEASE</version>       </dependency>    </dependencies>    <build>       <finalName>SpringMVCElectricityBillCalculation</finalName>       <sourceDirectory>src/main/java</sourceDirectory>       <plugins>          <plugin>             <groupId>org.apache.maven.plugins</groupId>             <artifactId>maven-surefire-plugin</artifactId>             <version>3.0.0-M3</version>             <configuration>                <testFailureIgnore>true</testFailureIgnore>                <shutdown>kill</shutdown>                <!-- Use it if required-->             </configuration>          </plugin>          <!-- This should be added to overcome Could not initialize class org.apache.maven.plugin.war.util.WebappStructureSerializer -->          <plugin>             <groupId>org.apache.maven.plugins</groupId>             <artifactId>maven-war-plugin</artifactId>             <version>3.3.2</version>          </plugin>       </plugins>    </build> </project> 

Bean class

Person.java

Java
public class Person {        private int id;     private String name;         private String serviceNumber;     private int consumedUnits;     private String gender;      public int getConsumedUnits() {         return consumedUnits;     }      public void setConsumedUnits(int consumedUnits) {         this.consumedUnits = consumedUnits;     }      public String getGender() {         return gender;     }      public void setGender(String gender) {         this.gender = gender;     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public String getServiceNumber() {         return serviceNumber;     }      public void setServiceNumber(String serviceNumber) {         this.serviceNumber = serviceNumber;     }  } 

Controller class

PersonController.java

Java
import java.sql.SQLException;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView;  import com.persons.beans.Person; import com.persons.dao.PersonDao;  @Controller @SessionAttributes("person") public class PersonController {     // @Autowired     PersonDao dao;      @Autowired     public PersonController(PersonDao dao) {         this.dao = dao;     }          @ModelAttribute("person")     public Person getPerson() {         return new Person();     }      // for searchform     @RequestMapping("/personsearchform")     public String searchform(Model m) {         m.addAttribute("command", new Person());         return "personsearchform";     }      // It provides check persons and calculate the amount based on consumed units     @RequestMapping(value = "/calculateAmount", method = RequestMethod.POST)     public ModelAndView calculateAmountForConsumedUnits(@ModelAttribute("person") Person person) {          ModelAndView mav = null;         Person person1 = null;         try {             if (person.getName() != null && person.getName() != "") {                 person1 = dao.getPersonsByName(person.getName());             }             if (person.getServiceNumber() != null && person.getServiceNumber() != "") {                 person1 = dao.getPersonsByServiceNumber(person.getServiceNumber());             }             mav = new ModelAndView("welcome");             if (null != person1) {                 System.out.println(person1.getId() + "..." + person1.getName() + ".." + person1.getServiceNumber()                 + "..consumed units.." + person1.getConsumedUnits());                 boolean isAvailable = false;                 int consumedUnits = person1.getConsumedUnits();                 int electricityChargesNeedToPay = 0;                 if (consumedUnits <= 100) {                     electricityChargesNeedToPay = consumedUnits * 10;                 }                 if (consumedUnits <= 200) {                     electricityChargesNeedToPay = (100 * 10) + (consumedUnits - 100) * 15;                 }                 if (consumedUnits <= 300) {                     electricityChargesNeedToPay = (100 * 10) + (100 * 15) + (consumedUnits - 200) * 20;                 }                 if (consumedUnits > 300) {                     electricityChargesNeedToPay = (100 * 10) + (100 * 15) + (100 * 20) + (consumedUnits - 300) * 25;                 }                                   System.out.println("electricityChargesNeedToPay.."+electricityChargesNeedToPay);                 mav.addObject("firstname", person1.getName());                 mav.addObject("servicenumber", person1.getServiceNumber());                 mav.addObject("consumedunits", person1.getConsumedUnits());                 mav.addObject("electricitycharges", electricityChargesNeedToPay);             }         else {             mav.addObject("firstname", person1.getName());             mav.addObject("electricitycharges", "Not present in the database");             //mav.addObject("location", person.getLocation());         }         } catch (SQLException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }          return mav;     }  } 

DAO class

PersonDao.java

Java
package com.persons.dao;  import java.sql.SQLException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import com.persons.beans.Person;  public class PersonDao {        JdbcTemplate template;      public void setTemplate(JdbcTemplate template) {         this.template = template;     }      public Person getPersonsByName(String personName) throws SQLException {         String sql = "select * from personsdetails where name=?";         return template.queryForObject(sql, new Object[] {personName},                 new BeanPropertyRowMapper<Person>(Person.class));     }          public Person getPersonsByServiceNumber(String serviceNumber) throws SQLException {         String sql = "select * from personsdetails where serviceNumber=?";         return template.queryForObject(sql, new Object[] {serviceNumber},                 new BeanPropertyRowMapper<Person>(Person.class));     }          public Person getPersonsById(int id) throws SQLException {         String sql = "select * from personsdetails where id =?";         return template.queryForObject(sql, new Object[] { id },                 new BeanPropertyRowMapper<Person>(Person.class));     }          public Person getPersonsByConsumedUnits(int consumedUnits) throws SQLException {         String sql = "select * from personsdetails where consumedUnits=?";         return template.queryForObject(sql, new Object[] { consumedUnits },                 new BeanPropertyRowMapper<Person>(Person.class));     }  } 

Let us see the JSP files

indexPageForFindingElectricityCharges.jsp

HTML
 <center><B><a href="personsearchform">Electricity Charge calculation</a></B></center> 

personsearchform.jsp

HTML
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>   <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"                  "http://www.w3.org/TR/html4/loose.dtd"> <html>    <head>       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">       <title>Electricity charge calculation</title>    </head>    <body>       <h1>Electricity charge calculation</h1>       <form:form  method="post" action="/SpringMVCElectricityBillCalculation/calculateAmount"  >          <table >             <tr>                <td>Person Name : </td>                <td>                   <form:input path="name"/>                </td>             </tr>             <tr>                <td>  (Or) </td>             </tr>             <tr>                <td>Service Number : </td>                <td>                   <form:input path="serviceNumber"/>                </td>             </tr>             <tr>                <td> </td>                <td><input type="submit" value="Calculate Electricity charge" /></td>             </tr>          </table>       </form:form>    </body> </html> 

Output:

Spring MVC with MySQL Output
 

We can search either by Person Name or Service Number

SearchBy PersonName

SearchBy PersonName Output
 

SearchBy Service Number

SearchBy Service Number Output
 

We can test the same by using MockMvc + JUnit

PersonControllerTest.java

Java
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;  import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext;  import com.persons.beans.Person; import com.persons.controllers.PersonController; import com.persons.dao.PersonDao;  @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-servlet.xml" }) @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration public class PersonControllerTest {        @InjectMocks     private PersonController personController;       private MockMvc mockMvc;      @Autowired     private PersonDao dao;          @Autowired     WebApplicationContext webApplicationContext;      @Before     public void setup() {         MockitoAnnotations.initMocks(this);         this.mockMvc = MockMvcBuilders.standaloneSetup(personController).build();      }       @Test     // 404 error thrown when coming from invalid resources     public void testCreateSearchPersonsPageFormInvalidUser() throws Exception {         this.mockMvc.perform(get("/"))         .andExpect(status().isNotFound());     }           @Test        // positive checks for Name       public void testCheckConsumedUnitsByName() throws Exception {            Person person = new Person();            person.setName("personA");            person = dao.getPersonsByName(person.getName());           Assert.assertEquals(1, person.getId());           Assert.assertEquals("123-456", person.getServiceNumber());           Assert.assertEquals(250, person.getConsumedUnits());       }              @Test        // Negative checks for Name       public void testCheckConsumedUnitsByNameForNegative() throws Exception {            Person person = new Person();            person.setName("personA");            person = dao.getPersonsByName(person.getName());           Assert.assertNotEquals(2, person.getId());           Assert.assertNotEquals("asd-123", person.getServiceNumber());           Assert.assertNotEquals(1500, person.getConsumedUnits());           Assert.assertNotEquals("Male", person.getGender());       }               @Test        // Negative checks + Positive       public void testCheckConsumedUnits() throws Exception {            Person person = new Person();            person.setConsumedUnits(250);           person = dao.getPersonsByConsumedUnits(person.getConsumedUnits());           Assert.assertNotEquals(10, person.getId());           Assert.assertNotEquals("ST-123", person.getServiceNumber());           Assert.assertEquals("Female", person.getGender());       }        @Test        // Positive  checks for consumedunits       public void testCheckConsumedUnitsPositive() throws Exception {            Person person = new Person();            person.setConsumedUnits(500);           person = dao.getPersonsByConsumedUnits(person.getConsumedUnits());           Assert.assertEquals(5, person.getId());           Assert.assertEquals("146-189", person.getServiceNumber());           Assert.assertEquals("personE", person.getName());           Assert.assertEquals("female", person.getGender());       }              @Test        // Negative + Positive checks       public void testCheckConsumedUnitsById() throws Exception {            Person person = new Person();            person.setId(2);            person = dao.getPersonsById(person.getId());           Assert.assertEquals(350, person.getConsumedUnits());           Assert.assertNotEquals("personZ", person.getName());           Assert.assertNotEquals("Gen-123", person.getServiceNumber());       }              @Test        // Positive checks for ID       public void testCheckConsumedUnitsByIdPositiveCheck() throws Exception {            Person person = new Person();            person.setId(5);            person = dao.getPersonsById(person.getId());           Assert.assertEquals(500, person.getConsumedUnits());           Assert.assertEquals("personE", person.getName());           Assert.assertEquals("146-189", person.getServiceNumber());           Assert.assertEquals("female", person.getGender());       }               }     

On execution of this, we will get the below output if MySQL data (actual data) matches with the expected data as given in the code. If there is something wrong, we need to check with the logic as well as the data

JUnit Result
 

In this way, we can execute the projects and also write test case execution.


Next Article
Spring MVC with MySQL - Sample Project For Calculating Electricity Bill

P

priyarajtt
Improve
Article Tags :
  • Java
  • Project
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Difference Between @Controller and @RestController Annotation in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not directly affect the operation of the code they annotate. It does not change the action of the compiled program. Understanding the differ
    3 min read
    Spring MVC - @RequestParam Annotation
    The @RequestParam annotation is one of the most commonly used annotations in Spring MVC for handling HTTP request parameters. @RequestParam annotation enables Spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Key features of @RequestParam annotation
    5 min read
    Query String and Query Parameter in Spring MVC
    According to Wikipedia "A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a pag
    6 min read
    How to Make Post Request in Java Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    4 min read
    How to Make Delete Request in Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    4 min read
    How to Make get() Method Request in Java Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    3 min read
    Spring @RequestMapping Annotation with Example
    The @RequestMapping annotation in Spring MVC is one of the most important annotations used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to the handler method
    4 min read
    How to Capture Data using @RequestParam Annotation in Spring?
    The @RequestParam annotation enables Spring to capture input data that may be passed as a query, form data, or any arbitrary custom data. It is used to bind a web request parameter to a method parameter. Here, we are going to understand these two above lines, and we will see how we can capture data
    6 min read
    Spring @ResponseBody Annotation with Example
    Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compil
    4 min read
    Spring MVC Project - Retrieving Population, Area and Region Details using Rest API
    REST API is more popular nowadays as we can able to get a variety of information like Population, Area, region, sub-region, etc., One such REST API that we are going to see here is https://restcountries.com/v3.1/capital/<any capital of a country> Example: https://restcountries.com/v3.1/capital
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences