SSM框架整合
1.1 原始方式整合
1.准备工作
2.创建Maven工程
3.导入Maven坐标
参考:素材/配置文件/pom.xml文件
<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>
</properties>
<dependencies>
<!--spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--servlet和jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<!--mybatis相关-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
......
4.编写实体类
public class Account {
private int id;
private String name;
private double money;
//省略getter和setter方法
}
5.编写Mapper接口
public interface AccountMapper {
//保存账户数据
void save(Account account);
//查询账户数据
List<Account> findAll();
}
Mapper接口对应的配置文件:AccountMapper.xml
<mapper namespace="com.rg.mapper.AccountMapper">
<insert id="save" parameterType="com.rg.domain.Account">
insert into account values(#{id},#{name},#{money})
</insert>
<select id="findAll" resultType="account">
select * from account
</select>
</mapper>
6.编写Service接口
public interface AccountService {
void save(Account account); //保存账户数据
List<Account> findAll(); //查询账户数据
}
7.编写Service接口实现
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public void save(Account account) {
accountMapper.save(account);
}
@Override
public List <Account> findAll() {
return accountMapper.findAll();
}
}
8.编写Controller
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
//保存
@RequestMapping(value = "/save",produces = "text/html;charset=utf-8")
@ResponseBody//保存成功后 返回一个提示信息,不是页面
public String save(Account account){//当前台name名称和实体属性名一致时,springMVC会自动进行属性封装
accountService.save(account);
return "保存成功";
}
//查询
@RequestMapping("/findAll")
public ModelAndView findAll(){
List <Account> accountList = accountService.findAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList", accountList);
modelAndView.setViewName("AccountList");
return modelAndView;
}
}
9.编写添加页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>保存账户信息表</h1>
<form action="${pageContext.request.contextPath}/account/save" method="post">
用户名称<input type="text" name="name"><br>
账户金额<input type="text" name="money"><br>
<input type="submit" value="保存"><br>
</form>
</body>
</html>
10.编写列表页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<th>账户id</th>
<th>账户名称</th>
<th>账户金额</th>
</tr>
<c:forEach items="${accountList}" var="account">
<tr>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
11.编写相应配置文件(文件参考目录:素材/配置文件)
•Spring配置文件:applicationContext.xml
•SprngMVC配置文件:spring-mvc.xml
•MyBatis映射文件:AccountMapper.xml
•MyBatis核心文件:sqlMapConfig.xml
•数据库连接信息文件:jdbc.properties
•Web.xml文件:web.xml
•日志文件:[log4j.xml](
12.测试添加账户
13.测试账户列表
1.2 Spring整合MyBatis
1.整合思路
添加组件扫描,将需要添加到IOC容器中的类,创建好对象,添加进去.
<!--组件扫描, 扫描service和mapper-->
<!-- 为啥需要:Spring能够从指定的classpath下自动扫描,侦测和实例化具有特定注解的bean。mapper和service中的实体可以用注解来搞,所以这俩需要进行扫描.其他的无需使用.-->
<context:component-scan base-package="com.rg">
<!-- 排除controller的扫描 (将spring和spring-mvc配置分开.)-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
2.将SqlSessionFactory配置到Spring容器中
<!-- 加载properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置数据源信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置sessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--加载创建工厂需要的datasource和配置文件.-->
<property name="dataSource" ref="dataSource"/>
<!-- 加载mybatis核心配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property>
</bean>
3.扫描Mapper,让Spring容器产生Mapper实现类
MapperScannerConfigurer:bean会扫描指定包和子包下所有的Mapper映射器,并自动调用getMapper方法,来调用映射器的实现方法。并将这些对象添加到Spring容器中
<!-- 配置MapperScannerConfigurer,这个配置中会自动生成映射器的实现方法,并调用,注入到Spring容器中.-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.rg.mapper"/>
</bean>
4.配置声明式事务控制
<!--配置声明式事务控制-->
<!-- 平台事务管理器-->
<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 = "*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.rg.service.impl.*.*(..))"/>
</aop:config>
总结:applicationContext.xml
<!--组件扫描, 扫描service和mapper-->
<!-- 为啥需要:Spring能够从指定的classpath下自动扫描,侦测和实例化具有特定注解的bean。mapper和service中的实体可以用注解来搞,所以这俩需要进行扫描.其他的无需使用.-->
<context:component-scan base-package="com.rg">
<!-- 排除controller的扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 加载properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置数据源信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置sessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 加载mybatis核心配置文件 因为要用到配置文件中的别名..-->
<property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property>
</bean>
<!-- spring扫描mapper所在的包 为mapper创建实现类 然后在业务层我们就可以直接注入使用了.-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.rg.mapper"/>
</bean>
<!-- 声明式事务控制-->
<!-- 平台事务管理器-->
<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 = "*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.rg.service.impl.*.*(..))"/>
</aop:config>
1.3 其他配置文件
1 spring-mvc.xml(前后无变化)
<!-- 组件扫描 主要扫描controller-->
<context:component-scan base-package="com.rg.controller"></context:component-scan>
<!-- 配置注解驱动-->
<!-- 提供Controller请求转发,json自动转换等功能-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置内部资源视图解析器 指定跳转的路径前后缀-->
<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 开发静态资源访问权限-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
2.sqlMapConfig.xml
整合之前的sqlMapConfig.xml
<configuration>
<!--加载properties配置文件-->
<properties resource="jdbc.properties"/>
<typeAliases>
<!--<typeAlias type="com.rg.domain.Account" alias="account"></typeAlias>-->
<!--指定报名则默认以类名首字母小写为其重命名.-->
<package name="com.rg.domain"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射-->
<mappers>
<!--<mapper resource="com\rg\mapper\AccountMapper.xml"/>-->
<!-- 使用报名,则将包下的全部加载-->
<package name="com.rg.mapper"/>
</mappers>
</configuration>
由于要将SqlSession的创建权给Spring,这样数据库连接池的配置可以整合到Spring中.在Spring和MyBatis都会用到com.rg.mapper下的类,所以我们可以将其声明成一个基础包,这样放在Spring中也可以使用了.
整合之后的配置文件:
<configuration>
<!--把splsession的创建交给spring. sqlSession创建时需要啥,在其配置文件中还得提供啥,如数据源信息,配置文件信息...-->
<typeAliases>
<!--<typeAlias type="com.rg.domain.Account" alias="account"></typeAlias>-->
<!--指定报名则默认以类名首字母小写为其重命名.-->
<package name="com.rg.domain"/>
</typeAliases>
</configuration>
3.web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<!-- spring监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- 标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法)。-->
<!-- 当值为0或者大于0时,表示容器在应用启动时就加载并初始化这个servlet;-->
</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>/*</url-pattern>
</filter-mapping>
</web-app>