Spring&SpringMVC&Mybatis 整合开发基础

数据库表的结构:

在这里插入图片描述

基本结构:

在这里插入图片描述

引入依赖:

<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 
https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wu.ssm</groupId>
  <artifactId>SSMDemo1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <!--  版本锁定 -->
  <properties>
  	<springVersion>5.2.0.RELEASE</springVersion>
  </properties>
  
  <!--  坐标导入 -->
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>${springVersion}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>${springVersion}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
    	<artifactId>spring-jdbc</artifactId>
    	<version>${springVersion}</version>
  	</dependency>
  	
  	<dependency>
  		<groupId>junit</groupId>
  		<artifactId>junit</artifactId>
  		<version>4.12</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
		  <artifactId>mybatis</artifactId>
		  <version>3.5.2</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>4.0.1</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet</groupId>
  		<artifactId>jstl</artifactId>
  		<version>1.2</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
    	<artifactId>mybatis-spring</artifactId>
    	<version>1.3.2</version>
  	</dependency>
  <dependency>
  		<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>8.0.22</version>
  	</dependency>
  <dependency>
  		<groupId>taglibs</groupId>
    	<artifactId>standard</artifactId>
    	<version>1.1.2</version>
  	</dependency>
  	<dependency>
  		<groupId>org.aspectj</groupId>
  		<artifactId>aspectjweaver</artifactId>
  		<version>1.9.0</version>
  	</dependency>
  	<dependency>
  		<!--  数据库连接池 -->
  		<groupId>com.mchange</groupId>
    	<artifactId>c3p0</artifactId>
    	<version>0.9.5.5</version>
  	</dependency>
  </dependencies>
</project>

创建mapper对象:

package com.wu.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.wu.pojo.Student;

public interface StudentMapper {
	void addStudent(Student student);
	void deleteStudentById(@Param("id") Integer id);
	void updateStudent(Student student);
	Student findStudentById(@Param("id") Integer id);
	List<Student> findAllStudent();
}

创建service接口及实现类:

package com.wu.service;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.wu.pojo.Student;

public interface IStudentService {
	void addStudent(Student student); // 增添学生
	void deleteStudentById(Integer id); // 通过Id删除学生
	void updateStudent(Student student); // 修改学生
	Student findStudentById(Integer id); // 通过Id查找学生
	List<Student> findAllStudent(); // 查找所有学生
}
package com.wu.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.wu.mapper.StudentMapper;
import com.wu.pojo.Student;

// 这里没有采用@Service注解方式交给Spring容器管理
public class StudentServiceImpl implements IStudentService{
	// 业务层调用持久层
	private StudentMapper studentMapper;
	
	public StudentMapper getStudentMapper() {
		return studentMapper;
	}

	public void setStudentMapper(StudentMapper studentMapper) {
		this.studentMapper = studentMapper;
	}

	@Override
	public void addStudent(Student student) {
		studentMapper.addStudent(student);
	}

	@Override
	public void deleteStudentById(Integer id) {
		studentMapper.deleteStudentById(id);
	}

	@Override
	public void updateStudent(Student student) {
		studentMapper.updateStudent(student);
	}

	@Override
	public Student findStudentById(Integer id) {
		return studentMapper.findStudentById(id);
	}

	@Override
	public List<Student> findAllStudent() {
		return studentMapper.findAllStudent();
	}
}

创建mapper配置文件:

<?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.wu.mapper.StudentMapper">

	<resultMap id = "studentResultMap" type = "Student">
		<id property = "studentId" column="student_id" />
		<result property = "studentName" column="student_name" />
		<result property = "studentGrade" column = "student_grade" />
	</resultMap>

	<insert id="addStudent" parameterType="Student">
		insert into student(student_name,student_id,student_grade) 
		values(#{studentName},#{studentId},#{studentGrade}) 
	</insert>
	<delete id="deleteStudentById" parameterType = "int">
		delete from student where student_id = #{id}
	</delete>
	<select id = "findStudentById" parameterType = "int" resultMap = "studentResultMap">
		select * from student where student_id = #{id}
	</select>
	<select id="findAllStudent" resultMap = "studentResultMap">
		select * from student
	</select>
	<update id="updateStudent" parameterType = "Student" >
		update student set student_name = #{studentName},student_grade = #{studentGrade} 
		where student_id = #{studentId}
	</update>
</mapper>

创建pojo类:

package com.wu.pojo;

public class Student {
	private String studentName;
	private Long studentId;
	private Integer studentGrade;
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public Long getStudentId() {
		return studentId;
	}
	public void setStudentId(Long studentId) {
		this.studentId = studentId;
	}
	public Integer getStudentGrade() {
		return studentGrade;
	}
	public void setStudentGrade(Integer studentGrade) {
		this.studentGrade = studentGrade;
	}
}

在src目录下创建xml配置文件:

spring-mvc.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">
	
	<!--  开启注解  -->
	<mvc:annotation-driven/>
	<!-- 扫描注解类  -->
	<context:component-scan base-package="com.wu.controller" />
	<!--  资源过滤 -->
	<mvc:default-servlet-handler/>
	
	<!-- 视图解析器  -->
	<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver"  id = "internalResourceViewResolver">
		<property name = "prefix" value = "/WEB-INF/jsp/"></property>
		<property name = "suffix"  value = ".jsp"></property>
	</bean>
</beans>

spring-dao.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"  
    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"> 
	
	
	<!--  关联数据库配置文件 -->
	<context:property-placeholder location="classpath:/database.properties"/>
	
	<bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name = "driverClass" value="${jdbc.driver}"/>
		<property name = "jdbcUrl"  value = "${jdbc.url}"/>
		<property name = "user"  value = "${jdbc.username}" />
		<property name = "password" value = "${jdbc.password}" />
		 
		 <property name ="maxPoolSize" value="${maxPoolSize}" /> <!--最大连接数-->
		<property name ="initialPoolSize" value="${initialPoolSize}"/> <!--初始化连接数-->
		<property name ="minPoolSize" value="${minPoolSize}" /> <!--最小连接数-->
		<property name = "autoCommitOnClose" value = "false" /> <!--  关闭连接后不自动提交 -->
	</bean>
	
	<bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
		<property name = "dataSource" ref = "dataSource" />
		<!--  绑定Mybatis的配置文件 -->
		<property name = "configLocation" value = "classpath:/mybatis-config.xml" />
	</bean>
	
	<!--  将实现Mapper接口类注入Spring容器中 -->
	<bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" >
		<property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" />
		<property name = "basePackage" value = "com.wu.mapper"/>
	</bean>
	
</beans>

spring-service.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: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.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd"> 
	
	<!--注解方式扫描包 <context:component-scan base-package = "com.wu.service" /> -->
	
	<bean id = "studentService" class = "com.wu.service.StudentServiceImpl">
		<property name="studentMapper" ref = "studentMapper" />
	</bean>
	
	<!--  声明事务配置 -->
	<bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name = "dataSource" ref = "dataSource" />
	</bean>
	
	<!--  配置事务通知 -->
	<tx:advice id = "txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" />
			<tx:method name = "delete*"/>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="update*"/>
		</tx:attributes>	
	</tx:advice>
	
	<!--  配置事务切入 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.wu.service.*.*(..))" id="txPointCut"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
	</aop:config>
</beans>

applicationContext.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<import  resource="classpath:spring-dao.xml"/>
	<import resource="classpath:spring-service.xml" />
	<import resource = "classpath:spring-mvc.xml"/>
</beans>

创建数据库配置文件:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
initialPoolSize=10
maxPoolSize=30
minPoolSize=10

创建mybatis全局配置文件:

<?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>
	<!-- 对name名称下的包取别名 -->
	<typeAliases>
		<package name="com.wu.pojo"></package>
	</typeAliases>
	<mappers>
		<mapper class = "com.wu.mapper.StudentMapper"/>
	</mappers>
</configuration>

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_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>SpringMVCDemo1</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>
	
	<servlet>
	  	<servlet-name>SpringMVC</servlet-name>
	  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	  	<!--  DispatcherServlet绑定Spring的配置文件  -->
	  	<init-param>
	  		<param-name>contextConfigLocation</param-name>
	  		<param-value>classpath:applicationContext.xml</param-value>
	  	</init-param>
	  	<!-- 启动级别为1  -->
	  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  		<servlet-name>SpringMVC</servlet-name>
  		<url-pattern>/</url-pattern>
  	</servlet-mapping>
	
	<!--  乱码问题解决 -->
	<filter>
		<filter-name>encodingFilter</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>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--  会话最长时间设置 -->
	<session-config>
		<session-timeout>20</session-timeout>
	</session-config>
</web-app>

控制器controller类:

package com.wu.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wu.pojo.Student;
import com.wu.service.IStudentService;

@Controller(value = "controller")
@RequestMapping("/student")
public class MyController {
	@Autowired
	@Qualifier(value = "studentService")
	private IStudentService studentService;
	
	
	
	@RequestMapping(path = "/findallstudent")
	public String findAllStudent(Model model) {
		List<Student> studentList = studentService.findAllStudent();
		model.addAttribute("studentList",studentList);
		return "FindAllStudent";
	}
	
	@RequestMapping(path = "/findstudentbyid",method = RequestMethod.POST)
	public String findStudentById(@RequestParam("id") int id,Model model) {
		Student student = studentService.findStudentById(id);
		model.addAttribute("student",student);
		return "FindStudentById";
	} 
	
	@RequestMapping(path = "/deletestudentbyid",method = RequestMethod.POST)
	public String deleteSutdentById(@RequestParam("id") int id,Model model) {
		studentService.deleteStudentById(id);
		return "DeleteStudentById";
	} 
	
	@PostMapping("/addstudent")
	public String addStudent(Student student,Model model) {
		model.addAttribute("student",student);
		studentService.addStudent(student);
		return "AddStudent";
	}
	
	@PostMapping("/updatestudent")
	public String updateStudent(Student student,Model model) {
		model.addAttribute("studnet",student);
		studentService.updateStudent(student);
		return "UpdateStudent";
	}
}

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>首页</title>
</head>
<body>
	<br/><hr/>
	<div align = "center">
	<table>
		<tr>
			<td>查询所有学生:</td>
			<td><a href = "/student/findallstudent">确认查询</a></td>
		</tr>
		<tr>
			<td>查找对应学号的学生:</td>
			<td>
			<form action = "/student/findstudentbyid" method = "post">
					<input type = "text" name = "id" "/>
					<input type = "submit" value = "查询"/>
			</form>
			</td>
		</tr>
		<tr>
			<td>删除对应学号的学生:</td>
			<td>
				<form action = "/student/deletestudentbyid" method = "post">
					<input type = "text" name = "id" />
					<input type = "submit"  value = "删除"/>
				</form>
			</td>
		</tr>
		<tr>
			<td>增添学生信息:</td>
			<td>
				<form action = "/student/addstudent" method = "post">
					姓名:<input type = "text" name = "studnetName" />
					学号:<input type = "text" name = “studentId” />
					班级:<input type = "text" name = “studentGrade” />
					<input type = "submit"  value = "添加"/>
				</form>
			</td>
		</tr>
		<tr>
			<td>修改学生信息:</td>
			<td>
			<form action = "/student/updatestudent" method = "post">
				待修改的学生学号:<input type = "text" name = “studentId” />
				修改后的姓名:<input type = "text" name = studentName />
				修改后的班级:<input type = "text" name = "studentGrade" />
				<input type = "submit"  value = "修改"/>
			</form>
			</td>
		</tr>
	</table>
	</div>
</body>
</html>

AddStudent.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>${requestScope.student.studentName}</title>
</head>
<body>
	<h1>增添成功</h1>
</body>
</html>

DeleteStudentById.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>${requestScope.student.studentName}</title>
</head>
<body>
	<h1>删除成功</h1>
</body>
</html>

FindAllStudent.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>Information Of Student</title>
</head>
<body>
	<div align = "center">
	<h1>学生信息表</h1>
	<table border = "1"   cellspacing = "0">
		<tr>
			<th>学生姓名</th>
			<th>学生学号</th>
			<th>学生班级</th>
		</tr>
		<c:forEach items = "${requestScope.studentList}" var = "s"> 
			<tr>
				<td align = "center">${pageScope.s.studentName}</td>
				<td align = "center">${pageScope.s.studentId}</td>
				<td align = "center">${pageScope.s.studentGrade}</td>	
			</tr>
		</c:forEach>
	</table>
	</div>
</body>
</html>

FindStudentById.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>${requestScope.student.studentName}</title>
</head>
<body>
	<br/><hr/>
	<div align = "center">
	学生姓名:${requestScope.student.studentName}<br/>
	学生学号:${requestScope.student.studentId}<br/>
	学生班级:${requestScope.student.studentGrade}
	</div>
</body>
</html>

UpdateStudent.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>${requestScope.student.studentName}</title>
</head>
<body>
	<h1>修改成功</h1>
</body>
</html>

结果:

在这里插入图片描述

查询

在这里插入图片描述
删除

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值