Bootstrap

SSM框架整合【案例演示】

需求描述

使用SSM框架完成对 account 表的增删改查操作。

目录结构

在这里插入图片描述

环境搭建

准备数据库和表记录

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);

在pom.xml文件中导入所需依赖坐标

<!--设置打包方式-->
<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>

    <!--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>

    <!--mybatis整合spring坐标-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>

    <!--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>

</dependencies>

★ 配置文件

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db
jdbc.username=root
jdbc.password=123

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: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="service"/>

    <!--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 生产sqlSession-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--给类起别名-->
        <property name="typeAliasesPackage" value="domain"/>
    </bean>

    <!--mapper映射扫描 MapperScannerConfigurer扫描该包下所有接口,生成代理对象存到IOC容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="dao"/>
    </bean>
    <!--spring整合mybatis结束...-->

    <!--spring的声明式事务-->
    <!--1.事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--2.开启事务注解的支持-->
    <tx:annotation-driven/>

</beans>

spring-mvc.xml

<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"
       xmlns="http://www.springframework.org/schema/beans"
       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">

    <!--1.组件扫描:只扫描controller包-->
    <context:component-scan base-package="controller"/>

    <!--2.mvc注解增强:处理器映射器及处理器适配器,支持json的解析-->
    <mvc:annotation-driven/>

    <!--3.视图解析器-->
    <bean id="resourceViewResolve" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--4.放行所有静态资源-->
    <mvc:default-servlet-handler/>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         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>
        <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>/*</url-pattern>
    </filter-mapping>

    <!-- 
		使用spring-web包中的ContextLoaderListener监听器,
		可以监听servletContext容器的创建和销毁,来同时创建或销毁IOC容器。 
	-->
    <!-- ★ 配置spring监听器 ★-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- ★ 加载Spring配置文件 ★ -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

</web-app>

domain实体类

public class Account {
    private Integer id;
    private String name;
    private Double money;
}

// get、set、toString方法略...

dao

public interface AccountDao {
    List<Account> findAll();

    void save(Account account);

    Account findById(Integer id);

    void update(Account account);

    void deleteBatch(Integer[] ids);
}

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="dao.AccountDao">

    <!--查询所有账户-->
    <select id="findAll" resultType="account">
        select * from account
    </select>

    <!-- 添加账户  void save(Account account);-->
    <insert id="save" parameterType="account">
        insert into account(name,money)  values(#{name},#{money})
    </insert>

    <!--根据ID查询账户信息   Account findById(Integer id);-->
    <select id="findById" parameterType="int" resultType="account">
        select * from account where id = #{id}
    </select>

    <!--更新账户-->
    <update id="update" parameterType="account">
        update account set name = #{name},money = #{money} where id = #{id}
    </update>

    <!--批量删除 void deleteBatch(Integer[] ids);  id in(1,2)-->
    <delete id="deleteBatch" parameterType="int">
        delete from account
        <where>
            <foreach collection="array" open="id in(" close=")" separator="," item="id">
                #{id}
            </foreach>
        </where>
    </delete>

</mapper>

service

AccountService接口:

public interface AccountService {

    List<Account> findAll();

    void save(Account account);

    Account findById(Integer id);

    void update(Account account);

    void deleteBatch(Integer[] ids);
}

AccountServiceImpl实现类:

@Service
@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;
    
    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public void deleteBatch(Integer[] ids) {
        accountDao.deleteBatch(ids);
    }
}

test

@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);
        }
    }
}

controller

AccountController:

@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";
    }

    @RequestMapping("/save")
    public String save(Account account) {
        accountService.save(account);
        // 跳转到findAll方法重新查询一次数据库进行数据的遍历展示
        return "redirect:/account/findAll";
    }

    @RequestMapping("/findById")
    public String findById(Integer id, Model model) {
        Account account = accountService.findById(id);
        // 存到model中
        model.addAttribute("account", account);
        // 视图跳转
        return "update";
    }

    @RequestMapping("/update")
    public String update(Account account) {
        accountService.update(account);
        return "redirect:/account/findAll";
    }

    @RequestMapping("/deleteBatch")
    public String deleteBatch(Integer[] ids) {
        accountService.deleteBatch(ids);
        return "redirect:/account/findAll";
    }
}

JSP文件

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>&nbsp;<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>

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>

update.jsp

<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>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <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>
        <script type="text/javascript">
        </script>
    </head>
    
    <body>
        <div style="text-align: right;padding-right: 50px"><a href="login.jsp">登录</a></div>
        <div align="center">
            <a
               href="list.jsp" style="text-decoration:none;font-size:33px">查询账户信息列表
            </a>
        </div>
    </body>
</html>
;