环境准备
1、创建数据库和表结构
create database ssm;
use ssm;
create table account( id int primary key auto_increment,
name varchar(20),
money double );
2、创建maven工程
配置pom.xml
<?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>com.hegong</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.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<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>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>
<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>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.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>
创建实体类
/**
* @author 14767
* 账户实体类
* 因为web服务器通常将那些暂时不活动但未超时的HttpSession对象转移到文件系统或数据库中保存,所以需要序列化
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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;
}
}
编写dao接口
/**
* @author 14767
* 账户dao接口
*/
public interface AccountDao {
/**
* 查询所有
* @return
*/
public List<Account> findAll();
/**
* 保存账户信息
* @param account
*/
public void saveAccount(Account account);
}
编写service接口和实现类
接口
/**
* @author 14767
*/
public interface AccountService {
/**
* 查询所有
* @return
*/
public List<Account> findAll();
/**
* 保存账户信息
* @param account
*/
public void saveAccount(Account account);
}
实现类
/**
* @author 14767
*/
public class AccountServiceImpl implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("业务层:查询所有账户。。。");
return null;
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层:保存账户");
}
}
编写账户控制器
/**
* @author 14767
* 账户控制器
*/
public class AccountController {
}
Spring框架代码的编写
搭建和测试Spring的开发环境
1、在SSM项目中创建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"
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层的注解,要忽略web层注解,因为web层让SpringMVC框架 去管理 -->
<context:component-scan base-package="com.hegong">
<!--配置哪些注解不扫描 -->
<!--表示Controller注解修饰的类不扫描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
2、在ssm项目中编写测试方法,进行测试
/**
* @author 14767
*
*/
public class SpringTest {
@Test
public void run(){
//加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
AccountService as = (AccountService)ac.getBean("accountService");
as.findAll();
}
}
执行该测试代码会出现警告,因为我们没有引入log4j的配置文件
3、引入log4j配置文件
# 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
Spring整合SpringMVC框架
搭建和测试SpringMVC的开发环境
1、在web.xml中配置DispatcherServlet前端控制器、编码过滤器、
<!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>
<!--解决中文乱码的过滤器 -->
<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>
<!--配置前端控制器 -->
<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>
</web-app>
2、 创建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">
<!--开启注解扫描,只扫描Controler注解 -->
<context:component-scan base-package="com.hegong">
<!--设置只扫描Controller注解 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</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 location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!--配置开启SpringMVC注解的支持 -->
<mvc:annotation-driven/>
</beans>
测试SpringMVC的框架搭建是否成功
1、编写index.jsp和list.jsp编写,超链接
index.jsp
list.jsp
2、给AccountController类,编写方法,进行测试
/**
* @author 14767
* 账户控制器
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层:查询所有账户信息。。。。");
return "list";
}
}
Spring整合SpringMVC的框架
现在如果我们想要从controller的方法中调用业务层的方法,那么我们需要业务层类的对象,这时候我们应该考虑使用依赖注入的方式来创建这个对象,但是如果我们使用spring的配置文件进行了该对象的依赖注入,会出现一个问题,我们的web 工程在启动的时候会先执行web.xml的配置文件,而该配置文件中的前端控制器只加载了springmvc.xml的配置文件,而该配置文件只扫描controller类的注解,也就是说serviec层的spring容器我们从始至终就没有创建过
我们如何解决这个问题呢?
我们可以使用servletContext域对象,因为该对象随着服务器的启动而创建,随着服务器的关闭而销毁
刚好可以帮助我们解决这个问题,我们可以使用监听器监听,该域对象,当这个域对象一被创建我们就加载spring的配置文件,这样我们在加载web.xml时前端控制器加载springmvc.xml中的controller的bean对象的时候里面注入的service就有值了,而不是空了
1、在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置监听器
ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文
件)。
<!--配置spring的监听器 ,默认只加载WEB-INF目录下的applicationContext.xml-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置配置文件的路径,因为配置文件在resources中部署到服务器上后再classes目录下,spring的监听器加载不到 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
2、在controller中注入service对象
/**
* @author 14767
* 账户控制器
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层:查询所有账户信息。。。。");
accountService.findAll();
return "list";
}
}
Spring整合Mybatis框架
搭建和测试MyBatis的环境
1、在web项目中编写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"></transactionManager>
<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="123456"/>
</dataSource>
</environment>
</environments>
<!--引入映射配置文件 -->
<mappers>
<package name="com.hegong.dao"/>
</mappers>
</configuration>
2、在AccountDao接口的方法上添加注解,编写SQL语句
/**
* @author 14767
* 账户dao接口
*/
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);
}
3、编写测试的方法
/**
* @author 14767
*/
public class MybatisTest {
/**
* 测试查询所有方法
* @throws Exception
*/
@Test
public void run1() throws Exception{
//加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建SqlSession对象
SqlSession session = factory.openSession();
//获取到代理对象
AccountDao dao = session.getMapper(AccountDao.class);
//查询所有账户信息
List<Account> list = dao.findAll();
for (Account account: list ) {
System.out.println(account);
}
//释放资源
session.close();
is.close();
}
/**
* 测试保存方法
* @throws Exception
*/
@Test
public void run2() throws Exception{
Account account = new Account();
account.setName("lalal");
account.setMoney(500d);
//加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建SqlSession对象
SqlSession session = factory.openSession();
//获取到代理对象
AccountDao dao = session.getMapper(AccountDao.class);
//查询所有账户信息
dao.saveAccount(account);
//提交事务
session.commit();
//释放资源
session.close();
is.close();
}
}
Spring整合MyBatis框架
spring整合mybatis框架同样是将dao的实现类对象加载到spring的ioc容器中,然后再service中注入daod的实现类对象
1、给applicationContext.xml配置文件添加新的配置
目的:把SqlMapConfig.xml配置文件中的内容配applicationContext.xml配置文件中这样就可以不配置SqlMapConfig.xml了,
在applicationContext.xml配置文件中加入,如下配置
<!--spring整合mybatis的框架 -->
<!--配置连接池 -->
<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"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--配置SqlSessionFactory工厂对象 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置AccountDao接口所在包 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hegong.dao"></property>
</bean>
添加如下配置之后就不用配置SqlMapConfig.xml了
2、在AccountDao接口中添加@Repository注解
3、 配置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>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"></tx:method>
</tx:attributes>
</tx:advice>
<!--配置AOP增强 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.hegong.service.impl.*ServiceImpl.*(..))"></aop:advisor>
</aop:config>
然后测试保存方法即可