SSM整合
搭建整合环境
1. 搭建整合环境
- 创建相应的数据库
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
money DOUBLE
);
- 创建Maven工程并导入相应坐标
- 创建ssm_parent父工程(打包pom)
- 创建ssm_web子模块(打包war)
- 创建ssm_service子模块(打包jar)
- 创建ssm_dao子模块(打包jar)
- 创建ssm_domain子模块(打包jar)
- web依赖于service,service依赖于dao,dao依赖于domain
<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.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>8.0.16</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>
- 编写实体类
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 +
'}';
}
}
- 编写dao
public interface AccountDao {
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 查询所有账户
* @return
*/
List<Account> findAll();
}
- 编写service和实现类
public interface AccountService {
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 查询所有账户
* @return
*/
List<Account> findAll();
}
@Service("accountService")
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
@Override
public void saveAccount(Account account) {
}
@Override
public List<Account> findAll() {
System.out.println("查询所有用户");
return null;
}
}
Spring框架代码的编写
- 创建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">
<!-- 开启Spring注解扫描
扫描的是service和dao层的注解,需要忽略web层的注解,因为web层使用SpringMVC进行管理
-->
<context:component-scan base-package="com.hsh.study">
<!-- 配置进行忽略的注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
- 测试service对象是否能注入成功
public class ServiceTest {
@Test
public void testService(){
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
AccountService accountService = ac.getBean("accountService", AccountService.class);
accountService.findAll();
}
}
Spring整合SpringMVC
1. 搭建和测试SpringMVC开发环境
- 在web.xml中配置DispathcerServlet前端控制器
<!-- 配置前端控制器 -->
<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:springmvc.xml</param-value>
</init-param>
<!-- 服务启动时创建对象 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 在web.xml中配置CharacterEncodingFilter锅炉其解决中文乱码
<!-- 配置过滤器 -->
<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>
- 配置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">
<!-- 配置Spring注解扫描 -->
<context:component-scan base-package="com.hsh.study">
<!-- 只扫描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 name="suffix" value=".jsp" />
</bean>
<!-- 设置静态资源不过滤 -->
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
<!-- 开启SpringMVC注解扫描知识 -->
<mvc:annotation-driven />
</beans>
- 测试SpringMVC框架是否搭建成功
- 编写index.jsp和list.jsp
<body>
<h1>SpringMVC框架测试</h1>
<a href="account/findAll">查询所有用户</a>
</body>
- 创建控制器类,进行测试
@Controller("accountController")
@RequestMapping("/account")
public class AccountController {
@RequestMapping("findAll")
public String findAll(){
System.out.println("表现层,查询所有用户!");
return "list";
}
}
2. Spring整合SpringMVC框架
- 在项目启动时,加载applicationContext.xml配置文件,在web.xml中配置ControllerListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml配置文件)
<!-- 配置Spring的监听器 -->
<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中注入service对象,调用方法进行测试
@Controller("accountController")
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("findAll")
public String findAll(){
System.out.println("表现层,查询所有用户!");
accountService.findAll();
return "list";
}
}
Spring整合MyBatis
1. 搭建MyBatis的环境
- 在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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<!-- 使用注解的方法 -->
<mappers>
<package name="com.hsh.study.dao"/>
</mappers>
</configuration>
- 在AccountDao接口方法上添加注解,编写SQL语句
public interface AccountDao {
/**
* 保存账户
* @param account
*/
@Insert("insert into account(name,money) values(#{name},#{money})")
void saveAccount(Account account);
/**
* 查询所有账户
* @return
*/
@Select("select * from account")
List<Account> findAll();
}
- 编写测试方法
public class DaoTest {
@Test
public void testFindAll() throws Exception{
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
SqlSession session = build.openSession();
AccountDao accountDao = session.getMapper(AccountDao.class);
List<Account> list = accountDao.findAll();
for (Account account : list){
System.out.println(account);
}
session.close();
is.close();
}
@Test
public void testSave() throws Exception{
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
SqlSession session = build.openSession();
AccountDao accountDao = session.getMapper(AccountDao.class);
Account account = new Account();
account.setName("王五");
account.setMoney(998.0);
accountDao.saveAccount(account);
session.commit();
session.close();
is.close();
}
}
2. Spring整合MyBatis框架
- 将sqlMapConfig.xml中的配置文件配置到applicationContext.xml中(sqlMapConfig.xml无用了,可以删除)
<!-- Spring整合MyBatis -->
<!-- 配置连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>
<!-- 配置工厂对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置接口所在的包 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name="basePackage" value="com.hsh.study.dao" />
</bean>
- 修改AccountDao接口
@Repository
public interface AccountDao {
...
}
- 修改业务层
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
- 配置Spring的事务管理
<!-- 配置事务管理 -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find" read-only="true"/>
<tx:method name="*" isolation="DEFAULT" />
</tx:attributes>
</tx:advice>
<!-- 配置AOP增强 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.hsh.study.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
- 编写前端页面
<body>
<h1>SpringMVC框架测试</h1>
<a href="account/findAll">查询所有用户</a>
<form action="account/saveAccount" method="post">
账户名称: <input type="text" name="name"><br>
账户金额: <input type="text" name="money"><br>
<input type="submit" value="保存">
</form>
</body>
<body>
<h1>所有用户信息</h1>
<table border="1" width="300px">
<tr>
<th>编号</th>
<th>账户名称</th>
<th>账户密码</th>
</tr>
<c:forEach var="list" items="${accounts}" varStatus="vs">
<tr>
<td>${vs.count}</td>
<td>${list.name}</td>
<td>${list.money}</td>
</tr>
</c:forEach>
</table>
</body>
- 编写控制器
@Controller("accountController")
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
/**
* 查询所有用户
* @return
*/
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<Account> accounts = accountService.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("accounts",accounts);
mv.setViewName("list");
return mv;
}
/**
* 保存账户
* @param account
* @return
*/
@RequestMapping("/saveAccount")
public String saveAccount(Account account){
accountService.saveAccount(account);
return "redirect:findAll";
}
}
整合完毕!