整合说明:SSM整合可以使用多种方式,咱选择XML + 注解的方式
整合的思路:①先搭建整合的环境;②完成Spring的配置搭建;③再使用Spring整合SpringMVC框架;④最后使用Spring整合MyBatis框架;
(1)创建数据库和表结构
create database ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);
(2)创建maven的工程
<!-- 版本锁定 -->
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${
mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${
log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${
slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${
slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${
mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
(3)编写实体类Account(按照数据库写)
(4)创建Service接口和实现类
(5)编写测试方法Test
@Test
public void run(){
//创建工程 加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取service 对象 调用方法
AccountService service = ac.getBean(AccountService.class);
service.findAll();
}
(6)applicationContext.xml开启注解扫描
<context:component-scan base-package="cn.tx.serive"/>
(1)在web.xml中配置DispatcherServlet前端控制器
<!--配置前端控制器-->
<servlet>
<!---->
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc.xml配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--启动加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
(2)在web.xml中配置CharacterEncodingFilter过滤器解决中文乱码
<!--配置中文乱码的过滤器-->
<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>/*
(3)创建springmvc.xml的配置文件,编写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
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="cn.tx.Controller"></context:component-scan>
<!--配置视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--jsp文件所在的目录-->
<property name="prefix" value="/pages/"/>
<!--文件的后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--设置静态资源不过滤-->
<!--
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
-->
<!--开启对山坡springMVC注解的支持-->
<mvc:annotation-driven/>
</beans>
(4)测试SpringMVC的框架搭建是否成功
①编写index.jsp、suc.jsp和list.jsp编写,超链接
②创建AccountController类,编写方法,进行测试
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll.do")
public ModelAndView findAll(){
System.out.println("表现层:查询所有的账号...");
ModelAndView mv = new ModelAndView();
mv.setViewName("suc");
return mv;
}
}
①目的:在controller中能成功的调用service对象中的方法。
②在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。
步骤:(1)配置监听器;(2)加载类路径下的配置文件;(3)将spring注入到AccountController中,并注解调用方法;
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--加载类路径下的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
@Controller
@RequestMapping("/role")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/save.do")
public ModelAndView save(){
System.out.println("表现层:查询所有的账号...");
List<Account> list = accountService.findAll();
ModelAndView mv = new ModelAndView();
mv.setViewName("suc");
return mv;
}
}
(1)配置主配置文件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>
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射配置文件 -->
<mappers>
<!--
<mapper class="cn.tx.dao.AccountDao"/>
<mapper class="cn.tx.dao.UserDao"/>
-->
<package name="cn.tx.dao"/>
</mappers>
</configuration>
(2)配置接口AccountDao;
public interface AccountDao {
@Select("select * from account")
public List<Account> findAll();
}
(3)配置测试方法TestMyBaties;
public class TestMyBatis {
@Test
public void run() throws IOException {
/*加载配置文件*/
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//构建工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//创建session
SqlSession session = factory.openSession();
//获取到代理对象
AccountDao mapper = session.getMapper(AccountDao.class);
//调用方法
List<Account> list = mapper.findAll();
for (Account account : list) {
System.out.println(account);
}
//关闭资源
session.close();
inputStream.close();
}
}
目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
(1)在applicationContext.xml中配置连接池和扫描dao接口所在的包
<?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="cn.tx.serive"/>
<!--配置druid连接池-->
<!--配置开源连接池 Druid连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///ssm" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--spring 整合mybatis SqlSessionFactoryBean创建工厂对象-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置扫描dao接口所在的包-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sessionFactory"/>
<property name="basePackage" value="cn.tx.dao"/>
</bean>
</beans>
(2)AccountServiceImpl注入AccountDao
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层:查询所有的账号...");
return accountDao.findAll();
}
}
@Controller
@RequestMapping("/role")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/save.do")
public ModelAndView save(){
System.out.println("表现层:查询所有的账号...");
List<Account> list = accountService.findAll();
for (Account account : list) {
System.out.println(account);
}
ModelAndView mv = new ModelAndView();
mv.setViewName("suc");
return mv;
}
}
public interface AccountDao {
@Select("select * from account")
public List<Account> findAll();
}
(3)启动Tomcat服务器
上诉操作只能完成查询操作,为了满足增删改查,则需要配置事务
①配置声明式事务管理
<!--配置声明式事务管理-->
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务的通知-->
<tx:advice id="txAvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务的增强-->
<aop:config>
<aop:advisor advice-ref="txAvice" pointcut="execution(public * cn.tx.serive.*ServiceImpl.*(..))"/>
</aop:config>
②表单代码(写一个from表单,用于增加数据)
③controller代码
/**
* 保存
* @return
*/
@RequestMapping("/save.do")
public String save(Account account){
// 调用service,保存数据
accountService.save(account);
return "suc";
}
④service代码
public void save(Account account) {
accountDao.save(account);
}
⑤dao代码
@Insert("insert into account(name,money) values (#{name},#{money})")
void save(Account account) ;