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 - Sample Project For Finding Doctors Online with MySQL
Next article icon

Spring MVC - Sample Project For Finding Doctors Online with MySQL

Last Updated : 08 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. With MySQL as the backend, we can store all doctor details and by using Spring MVC functionality we can get the details of doctors as the online pattern. Let us see it as a maven project here.

MySQL Queries:

As we are getting the details via MySQL, let us have some data for it

DROP DATABASE IF EXISTS geeksforgeeks; CREATE DATABASE geeksforgeeks; USE geeksforgeeks;  DROP TABLE geeksforgeeks.DoctorsDetails;  CREATE TABLE DoctorsDetails (   id int(6) unsigned NOT NULL,   doctorName varchar(50) NOT NULL,   doctorRegistrationNumber varchar(10) NOT NULL,   qualification varchar(30) NOT NULL,   gender varchar(10) DEFAULT NULL,   PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;  INSERT INTO geeksforgeeks.DoctorsDetails (id,doctorName, doctorRegistrationNumber, qualification,gender) VALUES (1,'doctorA','123-456','MDDCH','Female');  INSERT INTO geeksforgeeks.DoctorsDetails (id,doctorName, doctorRegistrationNumber, qualification,gender) VALUES (1,'doctorB','111-222','MSNeuro','Male');  INSERT INTO geeksforgeeks.DoctorsDetails (id,doctorName, doctorRegistrationNumber, qualification,gender) VALUES (1,'doctorC','222-444','MDGynae','Female');  INSERT INTO geeksforgeeks.DoctorsDetails (id,doctorName, doctorRegistrationNumber, qualification,gender) VALUES (1,'doctorD','199-998','MSNephro','Male');  INSERT INTO geeksforgeeks.DoctorsDetails (id,doctorName, doctorRegistrationNumber, qualification,gender) VALUES (1,'doctorE','444-666','MDCardio','Female');  SELECT * FROM geeksforgeeks.DoctorsDetails;  --If required, at last point of time we can truncate table truncate table geeksforgeeks.DoctorsDetails;

DBData Output:

DBData Output
 

Project Structure:

Project Structure
 

This is going to get executed as a maven project

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"           xmlns: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.doctors</groupId>    <artifactId>SpringMVCFindDoctorsOnline</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>SpringMVCFindDoctorsOnline 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>SpringMVCFindDoctorsOnline</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> 

We have to create a bean file and its structure should match with MySQL geeksforgeeks.DoctorsDetails

Doctor.java

Java
public class Doctor {        private int id;     private String doctorName;         private String doctorRegistrationNumber;         private String gender;     private String qualification;      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 getDoctorName() {         return doctorName;     }      public void setDoctorName(String doctorName) {         this.doctorName = doctorName;     }      public String getDoctorRegistrationNumber() {         return doctorRegistrationNumber;     }      public void setDoctorRegistrationNumber(String doctorRegistrationNumber) {         this.doctorRegistrationNumber = doctorRegistrationNumber;     }      public String getQualification() {         return qualification;     }      public void setQualification(String qualification) {         this.qualification = qualification;     }    } 

Let us come to controller java

DoctorController.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.doctors.beans.Doctor; import com.doctors.dao.DoctorDao;  @Controller @SessionAttributes("doctor") public class DoctorController {     // @Autowired     // will inject dao from xml file     DoctorDao dao;      @Autowired     public DoctorController(DoctorDao dao) {         this.dao = dao;     }          @ModelAttribute("doctor")     public Doctor getDoctor() {         return new Doctor();     }      // for searchform     @RequestMapping("/doctorsearchform")     public String searchform(Model m) {         m.addAttribute("command", new Doctor());         return "doctorsearchform";     }      // It provides a facility to check doctors online     @RequestMapping(value = "/checkDoctorsOnline", method = RequestMethod.POST)     public ModelAndView calculateAmountForConsumedUnits(@ModelAttribute("doctor") Doctor doctor) {          ModelAndView mav = null;         Doctor doctor1 = null;         try {             if (doctor.getDoctorName() != null && doctor.getDoctorName() != "") {                 doctor1 = dao.getDoctorsByName(doctor.getDoctorName());             }             if (doctor.getDoctorRegistrationNumber() != null && doctor.getDoctorRegistrationNumber() != "") {                 doctor1 = dao.getDoctorsByRegistrationNumber(doctor.getDoctorRegistrationNumber());             }             mav = new ModelAndView("welcome");             if (null != doctor1) {                 System.out.println(doctor1.getId() + "..." + doctor1.getDoctorName() + ".." + doctor1.getDoctorRegistrationNumber()                 + doctor1.getGender());                 boolean isAvailable = false;                                  mav.addObject("DoctorName", doctor1.getDoctorName());                 mav.addObject("RegistrationNumber", doctor1.getDoctorRegistrationNumber());                 mav.addObject("Gender", doctor1.getGender());                 mav.addObject("Qualification", doctor1.getQualification());             }         else {             mav.addObject("DoctorName", doctor1.getDoctorName());             mav.addObject("RegistrationNumber", "Not available Online");         }         } catch (SQLException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }          return mav;     }  } 

DAO class

DoctorDao.java

Java
import java.sql.SQLException;  import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate;  import com.doctors.beans.Doctor;  public class DoctorDao {     JdbcTemplate template;      public void setTemplate(JdbcTemplate template) {         this.template = template;     }      public Doctor getDoctorsByName(String doctorName) throws SQLException {         String sql = "select * from doctorsdetails where doctorname=?";         return template.queryForObject(sql, new Object[] {doctorName},                 new BeanPropertyRowMapper<Doctor>(Doctor.class));     }          public Doctor getDoctorsByRegistrationNumber(String registrationNumber) throws SQLException {         String sql = "select * from doctorsdetails where doctorRegistrationNumber=?";         return template.queryForObject(sql, new Object[] {registrationNumber},                 new BeanPropertyRowMapper<Doctor>(Doctor.class));     }          public Doctor getDoctorsById(int id) throws SQLException {         String sql = "select * from doctorsdetails where id =?";         return template.queryForObject(sql, new Object[] { id },                 new BeanPropertyRowMapper<Doctor>(Doctor.class));     }          public Doctor getDoctorsByGender(String gender) throws SQLException {         String sql = "select * from doctorsdetails where gender=?";         return template.queryForObject(sql, new Object[] {gender},                 new BeanPropertyRowMapper<Doctor>(Doctor.class));     }      } 

spring-servlet.xml

XML
<?xml version="1.0" encoding="UTF-8"?>   <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:context="http://www.springframework.org/schema/context"       xmlns:mvc="http://www.springframework.org/schema/mvc"       xsi:schemaLocation="           http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans.xsd           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context.xsd           http://www.springframework.org/schema/mvc           http://www.springframework.org/schema/mvc/spring-mvc.xsd">       <context:component-scan base-package="com.SpringMVCFindDoctorsOnline.controllers"></context:component-scan>          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">             <property name="prefix" value="/WEB-INF/jsp/"></property>             <property name="suffix" value=".jsp"></property>         </bean>          <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">             <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>             <property name="url" value="jdbc:mysql://localhost:3306/geeksforgeeks?serverTimezone=UTC"></property>         <property name="username" value="root"></property>             <property name="password" value="admin"></property>         </bean>          <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">             <property name="dataSource" ref="ds"></property>         </bean>          <bean id="dao" class="com.doctors.dao.DoctorDao">             <property name="template" ref="jt"></property>         </bean>         </beans>  

JSP Pages

indexPage.jsp

HTML
<center><B><a href="doctorsearchform">Find Doctors Online</a></B></center> 

We would be getting a page like below

 

On click of the "Find Doctors Online" link, we can get the below page

doctorsearchform.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>Find Doctors Online</title>    </head>    <body>       <h1>Find Doctors Online</h1>       <form:form  method="post" action="/SpringMVCFindDoctorsOnline/checkDoctorsOnline"  >          <table >             <tr>                <td>Doctor Name : </td>                <td>                   <form:input path="doctorName"/>                </td>             </tr>             <tr>                <td>  (Or) </td>             </tr>             <tr>                <td>Registration Number : </td>                <td>                   <form:input path="doctorRegistrationNumber"/>                </td>             </tr>             <tr>                <td> </td>                <td><input type="submit" value="Check Doctors Online" /></td>             </tr>          </table>       </form:form>    </body> </html> 

Output:

 

Via Doctor Name/Registration Number, we can check. As "doctorA" is given , it will use "getDoctorsByName" and returns back the doctor details

 

Via Registration Number:

 

Similarly, we can check doctor details easily via the above ways.


Next Article
Spring MVC - Sample Project For Finding Doctors Online with MySQL

P

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

Similar Reads

    Difference Between @Component, @Repository, @Service, and @Controller Annotations 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 have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are goi
    4 min read
    Difference Between @Controller and @Service 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 have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.  Spring @Control
    5 min read
    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
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