1.创建一个数据库ssm,在该数据库中创建一个account表
代码如下
并且添加数据
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
money DOUBLE
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO account(NAME, money) VALUES('老闫', 122);
使用pom.xml导入依赖一定要注意版本的对应
说明一下版本
mysql版本:8.0.13
spring版本:5.0.3.RELEASE
c3p0版本:0.9.5.2(这个一定不能使用老的版本)
mybatis版本:2.0.5
mybatis-spring版本:2.0.5
主页要我的数据库式8.0以上的,所以版本在整了几个版本后,确定这几个版本一起可以整合ssm
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.kitey</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.3.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>8.0.13</mysql.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>compile</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>
<!--EL表达式的依赖包-->
<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>3.5.1</version>
</dependency>
<!--这个依赖用于整合mybatis和spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!--一定要使用对应版本的c3p0包
-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
Account代码:
这里特意说了一下实现序列化接口为了可以在不同的版本进行运行
package cn.kitey.domain;
import java.io.Serializable;
/**
* 账户信息实体类
*
* 为啥要实现序列化:序列化就是对实例对象的状态(State 对象属性而不包括对象方法)进行通用编码
* (如格式化的字节码)并保存,以保证对象的完整性和可传递性。
* 简而言之:序列化,就是为了在不同时间或不同平台的JVM之间共享实例对象
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
因为使用mybatis所以不需要创建实现类
注意这里添加了注解
这里特意解释一下
@Repository:它用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean
@Service: 通常作用在业务层,但是目前该功能与 @Component 相同
@Controller: 通常作用在控制层,但是目前该功能与 @Component 相同
@Component : 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次
为了实现这些注解我们需要在 XML 配置文件中启用Bean 的自动扫描功能,这可以通过context:component-scan/实现
package cn.kitey.dao;
import cn.kitey.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 账户接口 (这里我们使用mybatis实现,不需要书写该接口的实现类)
* 使用注解的方式进行
*/
@Repository //交给IOC容器
public interface AccountDao {
/**
* 查询所有用户的方法
* @return
*/
@Select("select * from account")
public List<Account> findAll();
/**
* 保存账户信息
* @param account
*/
@Insert("insert into account (name, money) values(#{name}, #{money})")
public void saveAccount(Account account);
}
AccountService接口
package cn.kitey.service;
import cn.kitey.domain.Account;
import java.util.List;
/**
* 实现层接口
*/
public interface AccountService {
public List<Account> findAll();
public void saveAccount(Account account);
}
该接口的实现类AccountServiceImpl
package cn.kitey.service.impl;
import cn.kitey.dao.AccountDao;
import cn.kitey.domain.Account;
import cn.kitey.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 实现层接口的实现类
*/
@Service("accountService") //添加注解,将其交给IOC容器管理
public class AccountServiceImpl implements AccountService {
//创建accountDao对象
@Autowired //自动注入
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层:查询所有用户");
List<Account> all = accountDao.findAll();
return all;
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层:保存用户!");
accountDao.saveAccount(account);
}
}
package cn.kitey.controller;
import cn.kitey.domain.Account;
import cn.kitey.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* 账户web控制层(表现层)
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired //自动注入
private AccountServiceImpl accountService;
/**
*
* @param model 获取存储对象
* @return
*/
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("查询所有用户!");
List<Account> all = accountService.findAll();
model.addAttribute("list",all);
return "list";
}
@RequestMapping("/save")
public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response){
accountService.saveAccount(account);
//重定向
try {
response.sendRedirect(request.getContextPath() + "/account/findAll");
} catch (IOException e) {
e.printStackTrace();
}
}
}
index.jsp
<%--
Created by IntelliJ IDEA.
User: 小风筝
Date: 2020/6/20
Time: 15:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<a href="account/findAll"> 测试查询</a> <br/>
测试数据保存
<br/>
<form action="account/save" method="post">
姓名:<input type="text" name="name" /><br>
金额:<input type="text" name="money" /><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
跳转的页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 小风筝
Date: 2020/6/20
Time: 15:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>list</title>
</head>
<body>
<h3>查询所有用户结果!</h3>
<c:forEach items="${list}" var="account">
${account.name}
</c:forEach>
</body>
</html>
该配置文件为SqlMapConfig.xml在使用后我们可以将其删除,因为我们会在spring的配置文件进行配置数据库连接,通过c3p0数据池进行连接
<?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"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///ssm?serverTimezone=UTC&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="25002500"></property>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<package name="cn.kitey.dao"></package>
</mappers>
</configuration>
在test中创建测试类
testMybatis
package cn.kitey.test;
import cn.kitey.dao.AccountDao;
import cn.kitey.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class TestMybatis {
@Test
public void test01() throws Exception {
InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
//创建sqlSession对象
SqlSession session = factory.openSession();
//获取代理对象
AccountDao mapper = session.getMapper(AccountDao.class);
//执行查询方法
List<Account> all = mapper.findAll();
for (Account account : all) {
System.out.println(account);
}
//关闭资源
session.close();
stream.close();
}
@Test
public void testSaveAccount() throws Exception {
//读取配置文件
InputStream resource = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取session对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resource);
SqlSession session = factory.openSession();
AccountDao mapper = session.getMapper(AccountDao.class);
Account account = new Account();
account.setName("Happy");
account.setMoney(new Double(1233));
mapper.saveAccount(account);
System.out.println("存储成功!");
//提交事务,这样数据才可以存储
session.commit();
session.close();
resource.close();
}
}
配置spring配置文件applicationContext这个步骤也是最困难,最重要的一个步骤了
1.首先要开启注解扫面,但是我们扫面的时候不能扫面controller注解,因为这个注解我们希望SpringMVC进行扫面,这样才能实现视图控制
2. 配置数据连接池,获取dataSource数据
3. 配置SqlSessionFactory,经行session的获取
4. 配置AccountDao接口所在的包
5. 为了执行数据的存储,我应该配置spring框架声明事务
6. 配置事务管理器DataSourceTransactionManager
7. 配置事务通知
8. 配置AOP增强
<?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">
<!--开启注解扫描,希望处理service和dao。但是controller不需要框架进行处理-->
<context:component-scan base-package="cn.kitey">
<!--配置controller注解不进行扫面-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
<!--Spring整合MyBatis-->
<!--配置数据连接池-->
<!--
我们这里一定要注意版本的对应
<mysql.version>8.0.13</mysql.version>
spring.version>5.0.3.RELEASE</spring.version>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
c3p0.version = 0.9.5.2
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
-->
<bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///ssm?serverTimezone=UTC&characterEncoding=utf-8"></property>
<property name="user" value="root"></property>
<property name="password" value="25002500"></property>
</bean>
<!--为了在AccountController中注入accountDao-->
<!--配置SqlSessionFactory工厂-->
<bean id = "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置Account接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.kitey.dao"></property>
</bean>
<!--配置Spring框架的声明式事务-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置findAll方法为只读的-->
<tx:method name="find**" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"></tx:method>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="accountOP" expression="execution(* cn.kitey.service.impl.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="accountOP"></aop:advisor>
</aop:config>
</beans>
<?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">
<!--开启注解扫描,只扫描Controller注解-->
<context:component-scan base-package="cn.kitey">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
</context:component-scan>
<!--配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置跳转的页面-->
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--过滤静态资源-->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
<!--过滤静态资源开启SpringMVC注解支持-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
1.配置监听器,让tomcat启动时,加载springIOC容易,及扫描applicationContext配置文件
2. 配置前端控制器,让tomcat开启时,扫描springMVC配置文件
3. 配置过滤器,解决中文乱码
<!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>
<!--配置监听器,让启动tomcat服务器时,加载springIOC容器-->
<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>
<!--配置前端控制器(核心控制器)-->
<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>
<!--启动服务器,创建Servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</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>/*
然后直接测试点击网页链接是否可以进行数据的操作
index.jso页面
测试查询
测试数据插入
因为在数据存贮的操作设置了重定向跳转到方法findAll则结果为
对了Kite的用户
上述就是基础的实现了ssm的整合,一起加油吧
2020/6/20/23:18