1.1 整合思路
springmvc+mybaits的系统架构:
第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
第二步:整合service层
通过spring管理 service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。
第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。
1.引入maven依赖:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.1.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.1.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- jstl/jsp el表达式 --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl --> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-impl</artifactId> <version>1.2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--日志依赖包--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency>
2.创建数据库信息文件 db.properties [在resources包下]:
db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/yh01_ssm_mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT db.username=root db.password=123456 #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000
3.创建日志文件log4j.properties [resourecs包下]:
### log4j.rootLogger=debug,stdout,logfile ##### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout ## log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.File=src/main/resources/logs/zr.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}%l%F%p%m%n
4.配置mybatis-config.xml [resourecs包下]:
<?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> <typeAliases> <package name="com.po" /> </typeAliases> </configuration>
5.配置spring-mybatis.xml [resourecs包下]:
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:db.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
6.配置spring-service.xml [resourecs包下]:
<?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-3.0.xsd"> <bean id="stuService" class="com.service.impl.StuServiceImpl"/> </beans>
7.配置springmvc.xml [resourecs包下]:
<?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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 添加注解模式 可以扫描controller、com.service、... 这里让扫描controller,指定controller的包--> <context:component-scan base-package="com"/> <!-- 配置注解处理器映射器,功能:寻找执行类Controller --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置sprigmvc视图解析器:解析逻辑视图 后台返回逻辑视图:index 视图解析器解析出真正物理视图: 前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsps/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
8.编写实体类Student [com.po包下]
package com.po; public class Student { private Integer id; private String username; private String password; private Integer clazznumber; private String clazzname; private int sex; private String address; private String email; private String phone; private int flag; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getClazznumber() { return clazznumber; } public void setClazznumber(Integer clazznumber) { this.clazznumber = clazznumber; } public String getClazzname() { return clazzname; } public void setClazzname(String clazzname) { this.clazzname = clazzname; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } @Override public String toString() { return "Student [id=" + id + ", username=" + username + ", password=" + password + ", clazznumber=" + clazznumber + ", clazzname=" + clazzname + ", sex=" + sex + ", address=" + address + ", email=" + email + ", phone=" + phone + ", flag=" + flag + "]"; } }
9.新建StuDao [com.dao包下]
package com.dao; import com.po.Student; import java.util.List; public interface StuDao { public Student FindStu(Integer id); public List<Student> FindStus(); public void InsertStu(Student stu); public void DeleteStu(Integer id); //完全按照传过来的数据进行更新 public void UpdateStu(Student stu); }
10.新建StuService接口 [com.service包下]:
package com.service; import com.po.Student; import java.util.List; public interface StuService { public Student FindStu(Integer id); public List<Student> FindStus(); public void InsertStu(Student stu); public void DeleteStu(Integer id); //完全按照传过来的数据进行更新 public void UpdateStu(Student stu); }
11.新建StuServiceImpl实现类 [com.service.impl包下]:
package com.service.impl; import com.dao.StuDao; import com.po.Student; import org.springframework.beans.factory.annotation.Autowired; import com.service.StuService; import java.util.List; public class StuServiceImpl implements StuService { @Autowired private StuDao stuDao; @Override public Student FindStu(Integer id){ Student stu=stuDao.FindStu(id); return stu; } @Override public List<Student> FindStus() { List<Student> stus=stuDao.FindStus(); return stus; } @Override public void InsertStu(Student stu) { stuDao.InsertStu(stu); } @Override public void DeleteStu(Integer id) { stuDao.DeleteStu(id); } @Override public void UpdateStu(Student stu) { stuDao.UpdateStu(stu); } }
12.新建StuController类 [com.controller包下]:
package com.controller; import com.dao.StuDao; import com.po.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.service.StuService; @Controller public class StuController { @Autowired private StuService stuService; @RequestMapping("/findStuById.do") public ModelAndView findStuById(){ ModelAndView mv=new ModelAndView(); Student stu=stuService.FindStu(1); mv.addObject("stu",stu); mv.setViewName("stu"); System.out.println(stu); return mv; } }
13.新建jsp [WEB-INF/jsps包下]:
<%-- Created by IntelliJ IDEA. User: 中国YH Date: 2019/10/22 Time: 14:54 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>学生信息</title> <h3>${stu.id}</h3> <h3>${stu.username}</h3> <h3>${stu.clazznumber}</h3> <h3>${stu.clazzname}</h3> <h3>${stu.address}</h3> <h3>${stu.sex}</h3> </head> <body> </body> </html>
14.配置web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <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:springmvc.xml</param-value> </init-param> </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> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!--在web.xml中,添加spring容器监听器,加载spring容器。--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </context-param> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
15.测试: