Java 新手如何使用Spring MVC 与 MySQL 集成?_bc

我们将解释集成Spring MVCMySQL所涉及的步骤。在 MySQL 中,我们将拥有充当应用程序支柱的必要数据。让我们看一个示例应用程序,其中包含一些学生的数据及其 NEET 分数。Spring MVC 应用程序将与 MySQL 交互并根据需要检索数据。

创建数据库和表涉及的步骤

第 1 步:

1.1: 创建数据库测试。

-- test 这里是数据库的名称

第 2 步:

使用测试;

第 3 步:

create table studentsdetails(id int auto_increment primary key,
name varchar(25),caste varchar(25),neetmarks int,gender varchar(10));

第四步:

-- 
insert into studentsdetails(name,caste,neetmarks,gender) values ('Geek1','OBC',600,'Female');
insert into studentsdetails(name,caste,neetmarks,gender) values ('Geek2','General',700,'Female');
insert into studentsdetails(name,caste,neetmarks,gender) values ('Geek3','General',600,'Male');
insert into studentsdetails(name,caste,neetmarks,gender) values ('Geek4','OBC',670,'Male');
insert into studentsdetails(name,caste,neetmarks,gender) values ('Geek5','SC',600,'Female');
insert into studentsdetails(name,caste,neetmarks,gender) values ('Geek6','SC',500,'Male');

第5步:从中选择数据

-- 从学生详细信息中选择;
select * from studentsdetails;

现在让我们在Spring MVC应用程序中执行必要的步骤,项目结构如下: 

Java 新手如何使用Spring MVC 与 MySQL 集成?_maven_02

 

编写文件:pom.xml

<project xmlns="http:///POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:///POM/4.0.0 http:///maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.students</groupId>
<artifactId>SpringMVCMedicalSeatAvailabilityBasedOnNEETMarks</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>SpringMVCMedicalSeatAvailabilityBasedOnNEETMarks Maven Webapp</name>
<url>http://</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.1</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 -->
	<!-- This is much required to connect to MySQL -->
<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>SpringMVCMedicalSeatAvailabilityBasedOnNEETMarks</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>
			<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>

	<plugin>
		<groupId>org.codehaus.mojo</groupId>
		<artifactId>tomcat-maven-plugin</artifactId>
		<version>1.0-beta-1</version>
	</plugin>
</plugins>
	
</build>
</project>

文件:spring-servlet.xml

这是与 MySQL 通信所必需的文件

<?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.students.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> 
<!-- According to the username and password that we use, the changes need to be done below -->
<!-- Generally username will be root and password will be empty or will come with a password
Hence accordingly change the data here -->

<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/test"></property> -->
<!-- Here test is the name of the database -->
<property name="url" value="jdbc:mysql://localhost:3306/test?user=root&password=password&serverTimezone=UTC"></property>
	
<!-- <property name="username" value="root"></property> 
<property name="password" value="password"></property> -->
</bean> 
	
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate"> 
<property name="dataSource" ref="ds"></property> 
</bean> 
	
<bean id="dao" class="com.students.dao.StudentDao"> 
<property name="template" ref="jt"></property> 
</bean>	 


</beans>

现在让我们进入“ bean类”。这个bean类中的字段应该相当于MySQL表结构。只有这样,沟通才会更容易、更有效。

文件:Student.java

// Java Program to Illustrate Student Class

// Class
public class Student {

	// Class data members

	// Map to 
	private int id;
	// Map to 
	private String name;
	// Map to studentsdetails.caste
	private String caste;
	// Map to studentsdetails.neetMarks
	private int neetMarks;
	// Map to studentsdetails.gender
	private String gender;

	// Getter and setter methods

	// Getter
	public int getNeetMarks() { return neetMarks; }

	// Setter
	public void setNeetMarks(int neetMarks)
	{
		this.neetMarks = neetMarks;
	}

	// Getter
	public String getGender() { return gender; }

	// Setter
	public void setGender(String gender)
	{
		this.gender = gender;
	}

	// Getter
	public int getId() { return id; }

	// Setter
	public void setId(int id) { this.id = id; }

	// Getter
	public String getName() { return name; }

	// Setter
	public void setName(String name) {  = name; }

	// Getter
	public String getCaste() { return caste; }

	// Setter
	public void setCaste(String caste)
	{
		this.caste = caste;
	}
}

现在要做数据库操作,我们需要DAO java文件

文件:StudentDao.java

// Java程序演示StudentDao类

// 导入所需的类
import com.students.beans.Student;
import java.sql.SQLException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

// Class
public class StudentDao {

	JdbcTemplate template;

	public void setTemplate(JdbcTemplate template)
	{
		this.template = template;
	}

	// 我们可以通过学生姓名的方式从MySQL中搜索数据
	public Student getStudentsByName(String studentName)
		throws SQLException
	{
		String sql
			= "select * from studentsdetails where name=?";
		return template.queryForObject(
			sql, new Object[] { studentName },
			new BeanPropertyRowMapper<Student>(
				Student.class));
	}

	// 我们可以通过种姓的方式从MySQL中搜索数据
	public Student getStudentsByCaste(String caste)
		throws SQLException
	{
		String sql
			= "select * from studentsdetails where caste=?";
		return template.queryForObject(
			sql, new Object[] { caste },
			new BeanPropertyRowMapper<Student>(
				Student.class));
	}

	// 我们可以通过id的方式从MySQL中搜索数据
	public Student getStudentsById(int id)
		throws SQLException
	{
		String sql
			= "select * from studentsdetails where id =?";
		return template.queryForObject(
			sql, new Object[] { id },
			new BeanPropertyRowMapper<Student>(
				Student.class));
	}

	// 我们可以通过以下方式从MySQL中搜索数据
	public Student getStudentsByNeetMarks(int neetMarks)
		throws SQLException
	{
		String sql
			= "select * from studentsdetails where neetMarks=?";
		return template.queryForObject(
			sql, new Object[] { neetMarks },
			new BeanPropertyRowMapper<Student>(
				Student.class));
	}
}

现在让我们看看控制器类

StudentController.java

// Java程序演示StudentController类

// 导入所需的类
import com.students.beans.Student;
import com.students.dao.StudentDao;
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;

// Class
@Controller
@SessionAttributes("student")
public class StudentController {

	// @Autowired
	// 它将从xml文件中注入dao
	StudentDao dao;

	@Autowired public StudentController(StudentDao dao)
	{
		// this keyword refers to current instance itself
		this.dao = dao;
	}

	@ModelAttribute("student") public Student getStudent()
	{
		return new Student();
	}

	// For searchform
	@RequestMapping("/studentsearchform")
	public String searchform(Model m)
	{
		m.addAttribute("command", new Student());
		return "studentsearchform";
	}

  // 它提供了检查学生并根据NEET分数确定医学座位可用性的模型对象

  // 更改这里的逻辑取决于个人
  // 为了展示一个例子,下面的计算是假设的。需要小心处理异常,
  // 因为与数据库交互
	@RequestMapping(value = "/checkByNeetMarks",
					method = RequestMethod.POST)
	public ModelAndView
	checkByNeetMarks(@ModelAttribute("student")
					Student student)
	{

		ModelAndView mav = null;
		Student student1;

		// 尝试块以检查异常
		try {
			student1
				= dao.getStudentsByName(student.getName());
			mav = new ModelAndView("welcome");

			if (null != student1) {
				System.out.println(
					student1.getId() + "..."
					+ student1.getName() + ".."
					+ student1.getCaste() + "..neet marks.."
					+ student1.getNeetMarks());
				boolean isAvailable = false;
				if (student1.getCaste().equalsIgnoreCase(
						"General")
					&& student1.getNeetMarks() >= 600) {
					isAvailable = true;
				}

				if (student1.getCaste().equalsIgnoreCase(
						"OBC")
					&& student1.getNeetMarks() >= 500) {
					isAvailable = true;
				}

				if (student1.getCaste().equalsIgnoreCase(
						"SC")
					&& student1.getNeetMarks() >= 400) {
					isAvailable = true;
				}

				mav.addObject("firstname",
							student1.getName());

				if (isAvailable) {
					mav.addObject(
						"availability",
						"Eligible to get Medical Seat");
				}

				else {
					mav.addObject(
						"availability",
						"Not eligible to get Medical Seat");
				}
				mav.addObject("caste", student1.getCaste());
				mav.addObject("neetmarks",
							student1.getNeetMarks());
			}
			else {
				mav.addObject("firstname",
							student.getName());
				mav.addObject(
					"availability",
					"Not present in the database");
				// mav.addObject("location",
				// student.getLocation());
			}
		}

		// 用于处理 SQL 异常的捕获块
		catch (SQLException e) {
			// 使用printStackTrace()方法显示异常及行号			
      e.printStackTrace();
		}

		return mav;
	}
}

上面的设置可以准备为war文件,并且可以部署在tomcat的webapps文件夹下。

在Tomcat启动时,可以使用以下命令调用上述应用程序

http://localhost:8080/SpringMVCMedicalSeatAvailabilityBasedOnNEETMarks/

由于这是一个样例工程,所以没有做太多美化

Java 新手如何使用Spring MVC 与 MySQL 集成?_bc_03

我们可以点击此链接并继续

点击链接后,我们将得到如下内容

Java 新手如何使用Spring MVC 与 MySQL 集成?_bc_04

检查 url 是否发生变化。所有内容均应与控制器对齐 

用例

Java 新手如何使用Spring MVC 与 MySQL 集成?_spring_05

 

根据写的逻辑,我们正在得到结果,这里 

  • “dmeo ”是为搜索指定的名称。它将根据“studentsdetails”表进行检查 
  • 带圆圈的表示请求映射的名称。 

这是一个示例应用程序,其中给出了与 MySQL 数据库交互的必要步骤。使用Spring MVC和MySQL,我们可以轻松地执行业务逻辑。