1. 需求和步骤分析
需求
使用ssm框架完成对 account 表的增删改查操作。
步骤分析
- 准备数据库和表记录
- 创建web项目
- 编写mybatis在ssm环境中可以单独使用
- 编写spring在ssm环境中可以单独使用
- spring整合mybatis
- 编写springMVC在ssm环境中可以单独使用
- spring整合springMVC
2. 环境搭建
2.1 准备数据库和表记录
1 2 3 4 5 6 7 8 9
| CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) DEFAULT NULL, `money` double DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `account`(`id`,`name`,`money`) values (1,'tom',1000), (2,'jerry',1000);
|
2.2 创建web项目
3. 编写mybatis在ssm环境中可以单独使用
需求:基于mybatis先来实现对account表的查询
3.1 相关坐标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <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>
|
3.2 Accoun实体
1 2 3 4 5
| public class Account { private Integer id; private String name; private Double money; }
|
3.3 AccountDao接口
1 2 3
| public interface AccountDao { public List<Account> findAll(); }
|
3.4 AccountDao.xml映射
1 2 3 4 5
| <?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.lagou.dao.AccountDao"> <select id="findAll" resultType="Account"> select * from account </select> </mapper>
|
3.5 mybatis核心配置文件
jdbc.properties
1 2 3 4
| jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_db jdbc.username=root jdbc.password=root
|
SqlMapConfig.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?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 resource="jdbc.properties"/> <typeAliases> <package name="com.lagou.domain"/> </typeAliases> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <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> <package name="com.lagou.dao"/> </mappers> </configuration>
|
3.6 测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class MyBatisTest { @Test public void testMybatis() throws Exception { InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(); AccountDao accountDao = sqlSession.getMapper(AccountDao.class); List<Account> list = accountDao.findAll(); for (Account account : list) { System.out.println(account); } sqlSession.close(); } }
|
4. 编写spring在ssm环境中可以单独使用
4.1 相关坐标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.5.RELEASE</version> </dependency>
|
4.2 AccountService接口
1 2 3
| public interface AccountService { public List<Account> findAll(); }
|
4.3 AccountServiceImpl实现
1 2 3 4 5 6 7 8
| @Service public class AccountServiceImpl implements AccountService { @Override public List<Account> findAll() { System.out.println("findAll执行了...."); return null; } }
|
4.4 spring核心配置文件
applicationContext.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.lagou.service"/> </beans>
|
4.5 测试代码
1 2 3 4 5 6 7 8 9 10 11
| @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class SpringTest { @Autowired private AccountService accountService; @Test public void testSpring() throws Exception { List<Account> list = accountService.findAll(); System.out.println(list); } }
|
5. spring整合mybatis
5.1 整合思想
将mybatis接口代理对象的创建权交给spring管理,我们就可以把dao的代理对象注入到service中此时也就完成了spring与mybatis的整合了。
5.2 导入整合包
1 2 3 4 5 6
| <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency>
|
5.3 spring配置文件管理mybatis
注意:此时可以将mybatis主配置文件删除。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| <?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.lagou.service"/> <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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="com.lagou.domain"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.lagou.dao"/> </bean> </beans>
|
5.4 修改AccountServiceImpl
1 2 3 4 5 6 7 8 9
| @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { return accountDao.findAll(); } }
|
6. 编写springMVC在ssm环境中可以单独使用
需求:访问到controller里面的方法查询所有账户,并跳转到list.jsp页面进行列表展示
6.1 相关坐标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <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>
|
6.2 导入页面资源

6.3 前端控制器DispathcerServlet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <?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_3_1.xsd" version="3.1"> <!--前端控制器--> <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>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>
|
6.4 AccountController和 list.jsp
1 2 3 4 5 6 7 8 9 10 11 12
| @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"; } }
|
1 2 3 4 5 6 7 8 9 10 11
| <c:forEach items="${list}" var="account"> <tr> <td><input type="checkbox" name="ids"></td> <td>${account.id}</td> <td>${account.name}</td> <td>${account.money}</td> <td><a class="btn btn-default btn-sm" href="update.jsp">修改</a> <a class="btn btn-default btn-sm" href="">删除</a> </td> </tr> </c:forEach>
|
6.5 springMVC核心配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <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.lagou.controller"/> <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>
|
7. spring整合springMVC
7.1 整合思想
spring和springMVC其实根本就不用整合,本来就是一家。
但是我们需要做到spring和web容器整合,让web容器启动的时候自动加载spring配置文件,web容器销毁的时候spring的ioc容器也销毁。
7.2 spring和web容器整合
ContextLoaderListener加载【掌握】
可以使用spring-web包中的ContextLoaderListener监听器,可以监听servletContext容器的创建和销毁,来同时创建或销毁IOC容器。
1 2 3 4 5 6 7 8
| <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>
|
7.3 修改AccountController
1 2 3 4 5 6 7 8 9 10 11 12
| @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"; } }
|
8. spring配置声明式事务
8.1 spring配置文件加入声明式事务
1 2 3 4 5 6
| <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
<tx:annotation-driven/>
|
1 2 3 4
| @Service @Transactional public class AccountServiceImpl implements AccountService { }
|
8.2 add.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <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="age">余额:</label> <input type="text" class="form-control" id="age" name="age" 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>
|
8.3 AccountController
1 2 3 4 5
| @RequestMapping("/save") public String save(Account account){ accountService.save(account); return "redirect:/account/findAll"; }
|
8.4 AccountService接口和实现类
1
| public void save(Account account);
|
1 2 3 4 5 6 7 8
| @Service @Transactional public class AccountServiceImpl implements AccountService { @Override public void save(Account account) { accountDao.save(account); } }
|
8.5 AccountDao
1
| void save(Account account);
|
AccountDao.xml
1 2 3
| <insert id="save" parameterType="Account"> insert into account (name, money) values (#{name}, #{money}) </insert>
|
9. 修改操作
9.1 数据回显
① AccountController
1 2 3 4 5
| @RequestMapping("/findById") public String findById(Integer id, Model model) { Account account = accountService.findById(id); model.addAttribute("account", account); return "update"; }
|
② AccountService接口和实现类
1
| Account findById(Integer id);
|
1 2 3 4
| @Override public Account findById(Integer id) { return accountDao.findById(id); }
|
③ AccountDao接口和映射文件
1
| Account findById(Integer id);
|
1 2 3
| <select id="findById" parameterType="int" resultType="Account"> select * from account where id = #{id} </select>
|
④ update.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <form action="${pageContext.request.contextPath}/account/update" method="post"> <input type="hidden" name="id" value="${account.id}"> <div class="form-group"> <label for="name">姓名:</label> <input type="text" class="form-control" id="name" name="name" value="${account.name}" placeholder="请输入姓名"> </div> <div class="form-group"> <label for="money">余额:</label> <input type="text" class="form-control" id="money" name="money" value="${account.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>
|
9.2 账户更新
① AccountController
1 2 3 4 5
| @RequestMapping("/update") public String update(Account account){ accountService.update(account); return "redirect:/account/findAll"; }
|
② AccountService接口和实现类
1
| void update(Account account);
|
1 2 3 4
| @Override public void update(Account account) { accountDao.update(account); }
|
③ AccountDao接口和映射文件
1
| void update(Account account);
|
1 2 3
| <update id="update" parameterType="Account"> update account set name = #{name},money = #{money} where id = #{id} </update>
|
10. 批量删除
10.1 list.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13
| <script> $('#checkAll').click(function() { $('input[name="ids"]').prop('checked', $(this).prop('checked')); }) $('#deleteBatchBtn').click(function() { if (confirm('您确定要删除吗?')) { if ($('input[name="ids"]:checked').length > 0) { $('#deleteBatchForm').submit(); } else { alert('想啥呢?') } } }) </script>
|
10.2 AccountController
1 2 3 4 5
| @RequestMapping("/deleteBatch") public String deleteBatch(Integer[] ids) { accountService.deleteBatch(ids); return "redirect:/account/findAll"; }
|
10.3 AccountService接口和实现类
1
| void deleteBatch(Integer[] ids);
|
1 2 3 4
| @Override public void deleteBatch(Integer[] ids) { accountDao.deleteBatch(ids); }
|
10.4 AccountDao接口和映射文件
1
| void deleteBatch(Integer[] ids);
|
1 2 3 4 5
| <delete id="deleteBatch" parameterType="int"> delete from account <where> <foreach collection="array" open="id in(" close=")" separator="," item="id"> #{id} </foreach> </where> </delete>
|