Spring MVC — пример проекта для поиска врачей в Интернете с помощью MySQL
Spring MVC Framework следует шаблону проектирования Model-View-Controller. Он используется для разработки веб-приложений. Он работает вокруг DispatcherServlet. DispatcherServlet обрабатывает все HTTP-запросы и ответы. Используя MySQL в качестве серверной части, мы можем хранить все сведения о врачах, а с помощью функциональности Spring MVC мы можем получать сведения о врачах в виде онлайн-шаблона. Давайте рассмотрим это как проект maven здесь.
Запросы MySQL:
Поскольку мы получаем детали через MySQL, давайте у нас есть некоторые данные для этого.
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;
Вывод данных БД:
Структура проекта:
Это будет выполнено как проект maven
пом.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 < 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 > < dependencies > < dependency > < groupId >junit</ groupId > < artifactId >junit</ artifactId > < version >4.12</ version > < scope >test</ scope > </ dependency > < 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 > < dependency > < groupId >org.apache.tomcat</ groupId > < artifactId >tomcat-jasper</ artifactId > < version >9.0.12</ version > </ dependency > < dependency > < groupId >javax.servlet</ groupId > < artifactId >servlet-api</ artifactId > < version >3.0-alpha-1</ version > </ dependency > < dependency > < groupId >javax.servlet</ groupId > < artifactId >jstl</ artifactId > < version >1.2</ version > </ dependency > < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >8.0.11</ version > </ dependency > < 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 > |
Мы должны создать bean-файл, и его структура должна соответствовать MySQL geeksforgeeks.DoctorsDetails.
Доктор.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; } } |
Перейдем к контроллеру java
ДокторКонтроллер.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; } } |
класс ДАО
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 =?" ; <
РЕКОМЕНДУЕМЫЕ СТАТЬИ |