1.1 整合思路
springmvc+mybaits的系统架构:
第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
第二步:整合service层
通过spring管理 service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。
第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。
1.引入maven依赖:
<dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.11version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>5.1.1.RELEASEversion> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>5.1.1.RELEASEversion> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>javax.servlet-apiartifactId> <version>4.0.1version> <scope>providedscope> dependency> <dependency> <groupId>javax.servlet.jsp.jstlgroupId> <artifactId>jstlartifactId> <version>1.2version> dependency> <dependency> <groupId>org.apache.taglibsgroupId> <artifactId>taglibs-standard-implartifactId> <version>1.2.5version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>3.4.6version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatis-springartifactId> <version>2.0.1version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>5.2.0.RELEASEversion> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>8.0.18version> dependency> <dependency> <groupId>commons-dbcpgroupId> <artifactId>commons-dbcpartifactId> <version>1.4version> dependency> <dependency> <groupId>log4jgroupId> <artifactId>log4jartifactId> <version>1.2.16version> dependency> <dependency> <groupId>commons-logginggroupId> <artifactId>commons-loggingartifactId> <version>1.1.3version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-log4j12artifactId> <version>1.7.7version> 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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:mapper/*.xml">property> <property name="configLocation" value="classpath:mybatis-config.xml" /> bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property> bean> <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"> <context:component-scan base-package="com"/> <mvc:annotation-driven>mvc:annotation-driven> <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 ListFindStus(); 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 ListFindStus(); 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 ListFindStus() { List 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 Applicationdisplay-name>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
web-app>
15.测试: