SSM整合
1.1 需求和步骤分析
需求
- 使用ssm框架完成对 account 表的增删改查操作。
步骤分析
1. 准备数据库和表记录
2. 创建web项目
3. 编写mybatis在ssm环境中可以单独使用
4. 编写spring在ssm环境中可以单独使用
5. spring整合mybatis
6. 编写springMVC在ssm环境中可以单独使用
7. spring整合springMVC
1.2 环境搭建
1)准备数据库和表记录
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)创建web项目
1.3 编写mybatis在ssm环境中可以单独使用
需求:基于mybatis先来实现对account表的查询
1)相关坐标
<?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.myproject</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<packaging>war</packaging>
<dependencies>
<!--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>
</dependencies>
</project>
2)Account实体
package com.myproject.domain;
public class Account {
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;
}
}
3)AccountDao接口
package com.myproject.dao;
import com.myproject.domain.Account;
import java.util.List;
public interface AccountDao {
/*
查询所有账户
*/
public List<Account> findAll();
}
4)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.myproject.dao.AccountDao">
<!--查询所有用户-->
<select id="findAll" resultType="com.myproject.domain.Account">
select * from account
</select>
</mapper>
5)mybatis核心配置文件
- jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db
jdbc.username=root
jdbc.password=root
- 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" />
<!--类型别名配置-->
<typeAliases>
<package name="com.myproject.domain"/>
</typeAliases>
<environments default="dev">
<environment id="dev">
<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>
<package name="com.myproject.dao"/>
</mappers>
</configuration>
6)测试代码
package com.myproject.test;
import com.myproject.dao.AccountDao;
import com.myproject.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 resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
List<Account> all = accountDao.findAll();
for (Account account : all) {
System.out.println(account);
}
sqlSession.close();
}
}
1.4 编写spring在ssm环境中可以单独使用
1)相关坐标
<!--spring坐标-->
<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>
2)AccountService接口
package com.myproject.service;
import com.myproject.domain.Account;
import java.util.List;
public interface AccountService {
public List<Account> findAll();
}
3)AccountServiceImpl实现
package com.myproject.service.impl;
import com.myproject.dao.AccountDao;
import com.myproject.domain.Account;
import com.myproject.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
// 需要用到AccountDao的代理对象
@Autowired
private AccountDao accountDao;
/*
测试spring在ssm环境中的单独使用
*/
@Override
public List<Account> findAll() {
List<Account> all = accountDao.findAll();
return all;
}
}
4)spring核心配置文件
<?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">
<!--配置IOC相关操作:开启注解扫描-->
<context:component-scan base-package="com.myproject.service"></context:component-scan>
</beans>
5)测试代码
package com.myproject.test;
import com.myproject.domain.Account;
import com.myproject.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> all = accountService.findAll();
for (Account account : all) {
System.out.println(account);
}
}
}
1.5 spring整合mybatis
1)整合思想
- 将mybatis接口代理对象的创建权交给spring管理,我们就可以把dao的代理对象注入到service中,此时也就完成了spring与mybatis的整合了。
2)导入整合包
<!--mybatis整合spring坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
3)spring配置文件管理mybatis
**注意:**此时可以将mybatis主配置文件删除。
<?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">
<!--配置IOC相关操作:开启注解扫描-->
<context:component-scan base-package="com.myproject.service"></context:component-scan>
<!--spring整合mybatis 开始-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<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 生产sqlSession-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.myproject.domain"/>
<!--引入加载mybatis的核心配置文件 如果核心配置文件没有作用的法,可以不用加载-->
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
</bean>
<!--mapper映射扫描 MapperScannerConfigurer扫面包下所有接口,生成代理对象存到IOC容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.myproject.dao" />
</bean>
<!--spring整合mybatis 结束-->
</beans>
4)修改AccountServiceImpl
package com.myproject.service.impl;
import com.myproject.dao.AccountDao;
import com.myproject.domain.Account;
import com.myproject.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
// 需要用到AccountDao的代理对象
@Autowired
private AccountDao accountDao;
/*
测试spring在ssm环境中的单独使用
*/
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
1.6 编写springMVC在ssm环境中可以单独使用
需求:访问到controller里面的方法查询所有账户,并跳转到list.jsp页面进行列表展示
1)相关坐标
<!--springMVC坐标-->
<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>
2)导入页面资源
3)前端控制器DispathcerServlet
<?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>DisptcherServlet</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>DisptcherServlet</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>
4)AccountController和 list.jsp
package com.myproject.controller;
import com.myproject.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
@Controller
@RequestMapping("/account")
public class AccountController {
/*
查询所有用户
*/
@RequestMapping("/findAll")
public String findAll(Model model) {
// 实现查询所有账户
ArrayList<Account> list = new ArrayList<Account>();
Account account1 = new Account();
account1.setId(1);
account1.setName("jim");
account1.setMoney(1000d);
Account account2 = new Account();
account2.setId(2);
account2.setName("jom");
account2.setMoney(2000d);
list.add(account1);
list.add(account2);
// 把封装好的list存到model中
model.addAttribute("list",list);
return "list";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>账户列表</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<style type="text/css">
td, th {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h3 style="text-align: center">账户信息列表</h3>
<div class="col-lg-2"></div>
<div class="col-lg-8">
<form action="${pageContext.request.contextPath}/account/deleteBatch" method="post" id="deleteBatchForm">
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th>
<input type="checkbox" id="checkAll">
<%--实现全选全不选效果--%>
<script>
$('#checkAll').click(function () {
$('input[name="ids"]').prop('checked',$(this).prop('checked'));
})
</script>
</th>
<th>编号</th>
<th>姓名</th>
<th>余额</th>
<th>操作</th>
</tr>
<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>
<tr>
<td colspan="9" align="center">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加账户</a>
<input class="btn btn-primary" type="button" value="删除选中" id="deleteBatchBtn">
</td>
</tr>
</table>
</form>
</div>
<div class="col-lg-2"></div>
</div>
</div>
</body>
<script>
/*给删除选中按钮绑定点击事件*/
$('#deleteBatchBtn').click(function () {
if(confirm('您确定要删除吗')){
if($('input[name=ids]:checked').length > 0){
/*提交表单*/
$('#deleteBatchForm').submit();
}
}else {
alert('想啥呢,没事瞎操作啥')
}
})
</script>
</html>
5)springMVC核心配置文件
<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">
<!--组件扫描: 只扫描controller-->
<context:component-scan base-package="com.myproject.controller" />
<!--mvc注解增强:处理器映射器及处理器适配器-->
<mvc:annotation-driven />
<!--视图解析器-->
<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<!--放行静态资源-->
<mvc:default-servlet-handler />
</beans>
1.7 spring整合springMVC
1)整合思想
- spring和springMVC其实根本就不用整合,本来就是一家。
- 但是我们需要做到spring和web容器整合,让web容器启动的时候自动加载spring配置文件,web容器销毁的时候spring的ioc容器也销毁。
2)spring和web容器整合
ContextLoaderListener加载【掌握】
- 可以使用spring-web包中的ContextLoaderListener监听器,可以监听servletContext容器的创建和销毁,来同时创建或销毁IOC容器。
<!--配置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>
3)修改AccountController
package com.myproject.controller;
import com.myproject.domain.Account;
import com.myproject.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();
// 把封装好的list存到model中
model.addAttribute("list",list);
return "list";
}
}
1.8 spring配置声明式事务
1)spring配置文件加入声明式事务
<!--spring的声明事务-->
<!--1. 事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--2. 开启事务注解的支持-->
<tx:annotation-driven />
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
}
2)add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>添加用户</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<center><h3>添加账户</h3></center>
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<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>
</div>
<div class="col-lg-3"></div>
</div>
</div>
</body>
</html>
3)AccountController
@RequestMapping("/save")
public String save(Account account) {
accountService.save(account);
// 跳转到findAll方法重新查询一次数据库进行数据的遍历展示
return "redirect:/account/findAll";
}
4)AccountService接口和实现类
package com.myproject.service;
import com.myproject.domain.Account;
import java.util.List;
public interface AccountService {
public List<Account> findAll();
void save(Account account);
}
package com.myproject.service.impl;
import com.myproject.dao.AccountDao;
import com.myproject.domain.Account;
import com.myproject.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 {
// 需要用到AccountDao的代理对象
@Autowired
private AccountDao accountDao;
/*
测试spring在ssm环境中的单独使用
*/
@Override
public List<Account> findAll() {
List<Account> all = accountDao.findAll();
return all;
}
/*
账户添加
*/
@Override
public void save(Account account) {
accountDao.save(account);
}
}
5)AccountDao
package com.myproject.dao;
import com.myproject.domain.Account;
import java.util.List;
public interface AccountDao {
/*
查询所有账户
*/
public List<Account> findAll();
void save(Account account);
}
6)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.myproject.dao.AccountDao">
<!--查询所有用户-->
<select id="findAll" resultType="com.myproject.domain.Account">
select * from account
</select>
<!--添加账户-->
<insert id="save" parameterType="account">
insert into account values(null,#{name}, #{money})
</insert>
</mapper>
1.9 修改操作
1.9.1 数据回显
① AccountController
@RequestMapping("/findById")
public String findById(Integer id, Model model) {
Account account = accountService.findById(id);
model.addAttribute("account", account);
return "update";
}
② AccountService接口和实现类
Account findById(Integer id);
@Override
public Account findById(Integer id) {
return accountDao.findById(id);
}
③ AccountDao接口和映射文件
Account findById(Integer id);
<select id="findById" parameterType="int" resultType="Account">
select * from account where id = #{id}
</select>
④ update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>添加用户</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<center><h3>更新账户</h3></center>
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<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>
</div>
<div class="col-lg-3"></div>
</div>
</div>
</body>
</html>
1.9.2 账户更新
① AccountController
@RequestMapping("/update")
public String update(Account account){
accountService.update(account);
return "redirect:/account/findAll";
}
② AccountService接口和实现类
void update(Account account);
@Override
public void update(Account account) {
accountDao.update(account);
}
③ AccountDao接口和映射文件
void update(Account account);
<update id="update" parameterType="Account">
update account set name = #{name},money = #{money} where id = #{id}
</update>
1.10 批量删除
1)list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>账户列表</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<style type="text/css">
td, th {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h3 style="text-align: center">账户信息列表</h3>
<div class="col-lg-2"></div>
<div class="col-lg-8">
<form action="${pageContext.request.contextPath}/account/deleteBatch" method="post" id="deleteBatchForm">
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th>
<input type="checkbox" id="checkAll">
<%--实现全选全不选效果--%>
<script>
$('#checkAll').click(function () {
$('input[name="ids"]').prop('checked',$(this).prop('checked'));
})
</script>
</th>
<th>编号</th>
<th>姓名</th>
<th>余额</th>
<th>操作</th>
</tr>
<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>
<tr>
<td colspan="9" align="center">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加账户</a>
<input class="btn btn-primary" type="button" value="删除选中" id="deleteBatchBtn">
</td>
</tr>
</table>
</form>
</div>
<div class="col-lg-2"></div>
</div>
</div>
</body>
<script>
/*给删除选中按钮绑定点击事件*/
$('#deleteBatchBtn').click(function () {
if(confirm('您确定要删除吗')){
if($('input[name=ids]:checked').length > 0){
/*提交表单*/
$('#deleteBatchForm').submit();
}
}else {
alert('想啥呢,没事瞎操作啥')
}
})
</script>
</html>
2)AccountController
@RequestMapping("/deleteBatch")
public String deleteBatch(Integer[] ids) {
accountService.deleteBatch(ids);
return "redirect:/account/findAll";
}
3)AccountService接口和实现类
void deleteBatch(Integer[] ids);
@Override
public void deleteBatch(Integer[] ids) {
accountDao.deleteBatch(ids);
}
4)AccountDao接口和映射文件
void deleteBatch(Integer[] ids);
<delete id="deleteBatch" parameterType="int">
delete from account
<where>
<foreach collection="array" open="id in(" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</delete>