SSM
需求和步骤分析
使用ssm框架完成对 account 表的增删改查操作
步骤分析
1. 准备数据库和表记录
2. 创建web项目
3. 编写mybatis在ssm环境中可以单独使用
4. 编写spring在ssm环境中可以单独使用
5. spring整合mybatis
6. 编写springMVC在ssm环境中可以单独使用
7. spring整合springMVC
环境搭建
创建web项目,导入依赖
<?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.soulboy</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<!--指定编码及版本-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.11</java.version>
<maven.compiler.source>1.11</maven.compiler.source>
<maven.compiler.target>1.11</maven.compiler.target>
</properties>
<!-- 打包方式 -->
<packaging>war</packaging>
</project>
环境搭建
- 准备数据库和表记录
CREATE DATABASE spring_db
use `spring_db`
CREATE TABLE `account` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) DEFAULT NULL,
`money` DOUBLE DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `account`(`id`,`name`,`money`) VALUES (5,'tom',1000),(6,'jerry',1000)
编写mybatis在ssm环境中可以单独使用
需求:基于mybatis先来实现对account表的查询
- 相关坐标
<!--mybatis坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
- Account实体
package com.soulboy.domain;
public class Account {
private Integer id;
private String name;
private Double money;
public Account(Integer id, String name, Double money) {
this.id = id;
this.name = name;
this.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;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
3.AccountDao接口
package com.soulboy.dao;
import com.soulboy.domain.Account;
import java.util.List;
public interface AccountDao {
/*
查询所有
*/
public List<Account> findAll();
}
- AccountDao.xml映射 (路径resources: com/soulboy/dao/AccountDao.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.soulboy.dao.AccountDao">
<select id="findAll" resultType="Account">
select * from account
</select>
</mapper>
- mybatis核心配置文件
src/main/resources/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>
<!-- 加载properties文件 -->
<properties resource="jdbc.properties"></properties>
<!-- 设置别名 -->
<typeAliases>
<!-- 方式一: 给单个实体起别名 -->
<!-- <typeAlias type="com.soulboy.domain.User" alias="user"></typeAlias> -->
<!-- 方式二: 批量起别名 -->
<package name="com.soulboy.domain"/>
</typeAliases>
<!-- 运行环境 -->
<environments default="development">
<environment id="development">
<!-- 当前的事务交由JDBC进行管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据源信息 POOLED:使用Mybatis的连接池 UNPOOLED:不使用连接池,每一次请求都会创建连接-->
<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>
<!-- 使用该方式: XML文件的全路径-->
<!--<mapper resource="com.soulboy/mapper/UserMapper.xml"></mapper>-->
<!-- 使用该方式: 接口和映射文件需要同包同名 -->
<!--<mapper class="com.soulboy.mapper.UserMapper"></mapper>-->
<!-- 批量加载映射: Mapper接口的包路径 -->
<package name="com.soulboy.dao"/>
</mappers>
</configuration>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:50000/spring_db?useSSL=false
jdbc.username=root
jdbc.password=123456
- 测试代码
com/soulboy/test/MybatisTest.java
package com.soulboy.test;
import com.soulboy.dao.AccountDao;
import com.soulboy.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.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void testMybatis() throws IOException {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
List<Account> accountList = accountDao.findAll();
for (Account account : accountList) {
System.out.println(account);
}
sqlSession.close();
}
}
编写spring在ssm环境中可以单独使用
1.相关坐标
<!-- spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- aspectj的织入(切点表达式需要用到该jar包) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.14</version>
</dependency>
<!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
- AccountService接口
package com.soulboy.service;
import com.soulboy.domain.Account;
import java.util.List;
public interface AccountService {
public List<Account> findAll();
}
- AccountServiceImpl实现
package com.soulboy.service.impl;
import com.soulboy.dao.AccountDao;
import com.soulboy.domain.Account;
import com.soulboy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
//System.out.println("findAll执行了……");
List<Account> list = accountDao.findAll();
return list;
}
}
- 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">
<!--注解扫描-->
<context:component-scan base-package="com.soulboy"></context:component-scan>
</beans>
- 测试代码
package com.soulboy.test.spring;
import com.soulboy.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private AccountService accountService;
@Test
public void testSpring() {
accountService.findAll();
}
}
spring整合mybatis
- 整合思想
将mybatis接口代理对象的创建权交给spring管理,我们就可以把dao的代理对象注入到service中,此时也就完成了spring与mybatis的整合了。 - 导入整合包
<!--mybatis整合spring坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
- spring配置文件管理mybatis
注意:此时可以将mybatis主配置文件删除。
src/main/resources/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">
<!--注解扫描-->
<context:component-scan base-package="com.soulboy"></context:component-scan>
<!--spring整合mybatis-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--SqlSessionFactory创建交给spring的IOC容器-->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!--数据库环境配置-->
<property name="dataSource" ref="dataSource"/>
<!--类型别名配置-->
<property name="typeAliasesPackage" value="com.soulboy.domain"/>
<!--如果要引入mybatis主配置文件,可以通过如下配置-->
<!--<property name="configLocation"
value="classpath:SqlMapConfig.xml"/>-->
</bean>
<!--映射接口扫描配置,由spring创建代理对象,交给IOC容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.soulboy.dao"/>
</bean>
</beans>
- 修改AccountServiceImpl
package com.soulboy.service.impl;
import com.soulboy.dao.AccountDao;
import com.soulboy.domain.Account;
import com.soulboy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
//System.out.println("findAll执行了……");
List<Account> list = accountDao.findAll();
return list;
}
}
- 测试
package com.soulboy.test.spring;
import com.soulboy.domain.Account;
import com.soulboy.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private AccountService accountService;
@Test
public void testSpring() {
List<Account> accountList = accountService.findAll();
for (Account account : accountList) {
System.out.println(account);
}
}
}
编写springMVC在ssm环境中可以单独使用
需求:访问到controller里面的方法查询所有账户,并跳转到list.jsp页面进行列表展示
- 相关坐标
<!--springMVC坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!--servlet坐标-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp坐标-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
- 导入页面资源
- 前端控制器DispathcerServlet
src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servletclass>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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--post中文处理-->
<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>
- AccountController
AccountController
package com.soulboy.controller;
import com.soulboy.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(Model model) {
List<Account> list = new ArrayList<>();
list.add(new Account(1,"张三",1000d));
list.add(new Account(2,"李四",1000d));
model.addAttribute("list", list);
return "list";
}
}
jsp页面
src/main/webapp/list.jsp
<c:forEach items="${list}" var="account">
<tr>
<td>
<input type="checkbox" name="ids" value="${account.id}">
</td>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
<td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/account/findById?id=${account.id}">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td>
</tr>
</c:forEach>
- springMVC核心配置文件
src/main/resources/spring-mvc.xml
<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="com.soulboy.controller"/>
<!--mvc注解增强-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--实现静态资源映射-->
<mvc:default-servlet-handler/>
</beans>
- 配置Tomcat并启动并测试
http://localhost:8080/ssm/account/findAll
spring整合springMVC
整合思想
spring和springMVC其实根本就不用整合,本来就是一家。
但是spring和web容器需要整合,让web容器启动的时候自动加载spring配置文件,web容器销毁的时候spring的ioc容器也销毁。
spring和web容器整合
ContextLoaderListener加载【掌握】
可以使用spring-web包中的ContextLoaderListener监听器,可以监听servletContext容器的创建和销毁,来同时创建或销毁IOC容器。
src/main/webapp/WEB-INF/web.xml
<!--spring 与 web容器整合-->
<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>
修改AccountController(注入service:controller调用service,service调用dao)
AccountController
package com.soulboy.controller;
import com.soulboy.domain.Account;
import com.soulboy.service.AccountService;
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 java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model) {
List<Account> list = accountService.findAll();
model.addAttribute("list", list);
return "list";
}
}
配置Tomcat并启动并测试
http://localhost:8080/ssm/account/findAll
spring配置声明式事务(XML或注解)
- spring配置文件加入声明式事务
applicationContext.xml
<!--事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启事务注解支持-->
<tx:annotation-driven/>
- service层添加@Transactional 注解
AccountServiceImpl
package com.soulboy.service.impl;
import com.soulboy.dao.AccountDao;
import com.soulboy.domain.Account;
import com.soulboy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
//System.out.println("findAll执行了……");
List<Account> list = accountDao.findAll();
return list;
}
}
- add.jsp
src/main/webapp/add.jsp
<form action="${pageContext.request.contextPath}/account/save" method="post">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="money">余额:</label>
<input type="text" class="form-control" id="money" name="money" placeholder="请输入余额">
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" />
<input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
</div>
</form>
- AccountController
@RequestMapping("/save")
public String save(Account account){
accountService.save(account);
return "redirect:/account/findAll";
}
- AccountService接口和实现类
接口
package com.soulboy.service;
import com.soulboy.domain.Account;
import java.util.List;
public interface AccountService {
public List<Account> findAll();
public void save(Account account);
}
实现类
package com.soulboy.service.impl;
import com.soulboy.dao.AccountDao;
import com.soulboy.domain.Account;
import com.soulboy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
//System.out.println("findAll执行了……");
List<Account> list = accountDao.findAll();
return list;
}
@Override
public void save(Account account) {
accountDao.save(account);
}
}
- AccountDao
package com.soulboy.dao;
import com.soulboy.domain.Account;
import java.util.List;
public interface AccountDao {
/*
查询所有
*/
public List<Account> findAll();
/*
增加用户
*/
void save(Account account);
}
- AccountDao.xml映射
AccountDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.soulboy.dao.AccountDao">
<select id="findAll" resultType="Account">
select * from account
</select>
<insert id="save" parameterType="Account">
insert into account (name, money) values (#{name}, #{money})
</insert>
</mapper>
- 测试:添加用户
http://localhost:8080/ssm/account/findAll