Student management system based on Spring MVC + Spring + MyBatis

Posted by burningkamikaze on Sat, 27 Nov 2021 04:41:08 +0100

Resource download: https://download.csdn.net/download/weixin_44893902/45602690

Exercise point design: fuzzy query, delete, add

1, Language and environment

  1. Implementation language: JAVA language.
  2. Environment requirements: MyEclipse/Eclipse + Tomcat + MySql.
  3. Use technology: Jsp+Servlet+JavaBean or spring MVC + Spring + mybatis.

2, Realize function

With the increase of the number of "Chaoyang accounting training college", it is necessary to make a student management system. The main functions are as follows:

1. The home page displays all student information by default, as shown in the figure.

2. When the mouse hovers over a row of data, the data is displayed in orange, as shown in the figure.

3. When the user inputs the student name, click search to complete the fuzzy query and display the query results, as shown in Figure 3.

4. When the user clicks delete, a prompt box will pop up. After the user clicks OK, the selected data will be deleted and the latest data will be displayed, as shown in Figure 4 and figure 5.


5. Click the "enter" link to open the new page. After filling in the relevant information, if you don't want to enter, click "Cancel" to return to the home page. Click the enter button to add the student information data to the database, and the page will jump to the list page to display the latest data

3, Database design

  1. Create a database (student_db).
  2. Create a data table (student) with the following structure.

4, Recommended implementation steps

1. The implementation steps of SSM version are as follows:
(1) Create database and data table and add test data (add at least 5 test data).
(2) Create a Web project, create various packages, and import the jar files required by the project.
(3) Add relevant SSM framework support.
(4) Various configuration files required by the configuration project (mybatis configuration file, spring configuration file, spring MVC configuration file).
(5) Create an entity class.
(6) Mapper interface required to create MyBatis operation database and its Xml mapping database operation statement file. (7) Create corresponding interfaces and implementation classes of business logic, implement corresponding businesses, and add references and injections to DAO/Mapper in the classes.
(8) Create the Controller class, add reference and injection to the business logic class in the Controller, and configure the spring MVC configuration file.
(9) Create relevant operation pages and beautify the pages with CSS.
(10) Realize various operation functions of the page and verify them in relevant places. The operation should be humanized.
(11) After debugging and running successfully, export relevant database files and submit them.

2. The implementation steps of JSP version are as follows:
(1) Build database and tables according to the above database requirements, and add test data.
(2) Create a Web project, create various packages, and import the jar files required by the project.
(3) Create an entity class.
(4) Create a Servlet to obtain different requests from users, and forward these requests to the corresponding business methods of the business processing layer.
(5) Create a business processing layer in which business methods are defined to implement system requirements, in which DAO methods need to be executed.
(6) Create a BaseDAO tool class and use JDBC to complete the query, deletion and addition of data table data.
(7) Write JSP pages to display the query results of data.

5, Implementation code

1. MySQL database

student_db

/*
 Date: 26/07/2021 19:44:05
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `studentName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `studentNo` int(11) NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `major` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `grade` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (2, 'Mei Hua Zhang', 135654621, 20, '0', 'Computer application', 'first grade');
INSERT INTO `student` VALUES (3, 'Zi Hao Wang', 5315641, 20, '1', 'Computer network technology', 'second grade');
INSERT INTO `student` VALUES (4, 'Li Yuheng', 13515681, 19, '0', 'Computer network technology', 'first grade');
INSERT INTO `student` VALUES (5, 'Zi Hao Wang', 13515681, 19, NULL, 'Computer network technology', 'second grade');

SET FOREIGN_KEY_CHECKS = 1;

2. Project Java code

directory structure

Student

JAR package:

src

com.controller

StudentController.java

package com.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.entity.Student;
import com.services.StudentService;

@Controller
public class StudentController {
	@Resource
	StudentService studentservice;

	@RequestMapping("student")
	public ModelAndView select(String keyword) {
		List<Student> selestudent = studentservice.selestudent(keyword);
		if (keyword == null || keyword.trim().equals("")) {
			keyword = "";
		}
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("selestudent", selestudent);
		modelAndView.setViewName("Student");
		return modelAndView;
	}

	@RequestMapping("delstu")
	public String delstu(Integer id) {
		int delStudent = studentservice.delStudent(id);
		return "redirect:/student.do";
	}

	@RequestMapping("addjsp")
	public String addjsp() {
		return "addStudent";
	}

	@RequestMapping("add")
	public String add(Student student) {
		int add = studentservice.add(student);
		return "redirect:/student.do";
	}

}

com.dao

StudentMapper.java

package com.dao;

import com.entity.Student;
import java.util.List;

public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    Student selectByPrimaryKey(Integer id);

    List<Student> selectAll();

    int updateByPrimaryKey(Student record);
    
    List<Student> likeStudents(String keyword);
}

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.dao.StudentMapper" >
  <resultMap id="BaseResultMap" type="com.entity.Student" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="studentName" property="studentname" jdbcType="VARCHAR" />
    <result column="studentNo" property="studentno" jdbcType="INTEGER" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="gender" property="gender" jdbcType="INTEGER" />
    <result column="major" property="major" jdbcType="VARCHAR" />
    <result column="grade" property="grade" jdbcType="VARCHAR" />
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from student
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.entity.Student" >
    insert into student (id, studentName, studentNo, 
      age, gender, major, 
      grade)
    values (#{id,jdbcType=INTEGER}, #{studentname,jdbcType=VARCHAR}, #{studentno,jdbcType=INTEGER}, 
      #{age,jdbcType=INTEGER}, #{gender,jdbcType=INTEGER}, #{major,jdbcType=VARCHAR}, 
      #{grade,jdbcType=VARCHAR})
  </insert>
  <select id="selectAll" resultMap="BaseResultMap" >
    select id, studentName, studentNo, age, gender, major, grade
    from student
  </select>
  
   <select id="likeStudents" resultMap="BaseResultMap" >
    select id, studentName, studentNo, age, gender, major, grade
    from student where studentName like "%"#{keyword}"%"
  </select>
</mapper>

com.entity

Student.java

package com.entity;

public class Student {
    private Integer id;

    private String studentname;

    private Integer studentno;

    private Integer age;

    private Integer gender;

    private String major;

    private String grade;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStudentname() {
        return studentname;
    }

    public void setStudentname(String studentname) {
        this.studentname = studentname == null ? null : studentname.trim();
    }

    public Integer getStudentno() {
        return studentno;
    }

    public void setStudentno(Integer studentno) {
        this.studentno = studentno;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major == null ? null : major.trim();
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade == null ? null : grade.trim();
    }
}

com.service.imp

StudentServiceImp.java

package com.service.imp;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dao.StudentMapper;
import com.entity.Student;
import com.services.StudentService;

@Service
public class StudentServiceImp implements StudentService {
	@Resource
	StudentMapper studenmapper;

	@Override
	public List<Student> selestudent(String keyword) {
		if (keyword == null || keyword.trim().equals("")) {
			List<Student> selectAll = studenmapper.selectAll();
			return selectAll;
		} else {
			List<Student> likeStudents = studenmapper.likeStudents(keyword);
			return likeStudents;
		}

	}

	@Override
	public int delStudent(Integer id) {
		int deleteByPrimaryKey = studenmapper.deleteByPrimaryKey(id);
		return deleteByPrimaryKey;
	}

	@Override
	public int add(Student student) {
		int insert = studenmapper.insert(student);
		return insert;
	}

}

com.services

StudentService.java

package com.services;

import java.util.List;
import com.entity.Student;

public interface StudentService {

	List<Student> selestudent(String keyword);
	
	int delStudent(Integer id);
	
	int add(Student student);
}

mybatis

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- alias -->
	<typeAliases>
		<package name="com.entity" />
	</typeAliases>
</configuration>

spring

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://www.springframework.org/schema/beans" 
	xmlns:p="http://www.springframework.org/schema/p" 
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.2.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd
	http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
	
	<!-- appoint spring Container read db.properties file -->
	<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
	<!-- Register connection pool with bean In container -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="driverClassName" value="${jdbc.driver}"></property>
		<property name="Url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- to configure SqlSessionFactory -->
	<bean class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- set up MyBatis Core profile -->
		<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
		<!-- set up data sources -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- to configure Mapper scanning -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- set up Mapper Scan package -->
		<property name="basePackage"  value="com.dao" />
	</bean>
	<!-- Configure transaction manager -->
		<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
			<property name="dataSource" ref="dataSource"></property>
		</bean>
		<!-- Enable annotation mode management AOP affair -->
		<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://www.springframework.org/schema/beans" 
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:mvc="http://www.springframework.org/schema/mvc" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
		<!-- to configure Service scanning -->
		<context:component-scan base-package="com" />
		
</beans>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://www.springframework.org/schema/beans" 
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:mvc="http://www.springframework.org/schema/mvc" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
		
		<!-- to configure Controller scanning -->
		<context:component-scan base-package="com.controller" />
		<!-- Configure annotation driven -->
		<mvc:annotation-driven />
		<!-- Configure view parser -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<!-- prefix -->
			<property name="prefix" value="/WEB-INF/jsp/" />
			<!-- suffix -->
			<property name="suffix" value=".jsp" />
		</bean>
</beans>

jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/student_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123456
jdbc.driver=com.mysql.jdbc.Driver

WebContent

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Student</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

JSP

Home.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path;
%>
<html>
<head>
<meta charset="utf-8">
<title>Sign in</title>
</head>
<body>
	<script type="text/javascript">
	window.location.href="<%=basePath%>
		/student.do";
	</script>
</body>
</html>

addStudent.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>add to</title>

</head>
<body>
	<form action="add.do" method="post">
			full name:<input type="text" name="studentname" value="${student.studentname }">
			<br> Admission number:
	<input type="text" name="studentno" value="${student.studentno}">
	<br> Student age:
	<input type="text" name="age" value="${student.age}">
	<br> Student gender:
	<input type="radio"  name="gender" value="1" <c:if test="${student.gender==1}">checked="checked"</c:if>>male 
	<input type="radio"  name="gender" value="0" <c:if test="${student.gender!=1}">checked="checked"</c:if>>female
	<br> major:
	<input type="text" name="major" value="${student.major}">
	<br> grade:
	<input type="text" name="grade" value="${student.grade}">
	<br>
	<div>
		<input type="submit" value="add to">
	</div>
		
	</form>

</body>
</html>

Student.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Student management</title>
</head>
<body>
	<form action="student.do">
	<input type="text" name="keyword"><input type="submit" value="query">
	</form>
	<table border="1px">
		<tr>
			<th>number</th>
		    <th>Student name</th>
		    <th>Admission number</th>
		    <th>Student age</th>
		    <th>Student gender</th>
		    <th>major</th>
		    <th>grade</th>
		    <th>operation</th>
		</tr>
		<c:forEach var="student" items="${selestudent }">
		<tr>
			<td>${student.id}</td>
		    <td>${student.studentname}</td>
		    <td>${student.studentno}</td>
		    <td>${student.age}</td>
		    <td>${student.gender} </td>
		    <td>${student.major}</td>
		    <td>${student.grade}</td>
		    <td>
		    <a href="delstu.do?id=${student.id }">delete</a>
		    <a href="addjsp.do">add to</a>
		    </td>
		    
		</tr>
		</c:forEach>
		
	</table>
	<span>common ${selestudent.size()}Data bar</span>
</body>
</html>

Topics: Java MySQL Mybatis Spring mvc