2021-06-20

本文详细介绍了SSM框架整合过程,包括web.xml中的配置、Maven依赖、DAO与Service层的配置、以及Spring MVC控制器的实现。重点展示了如何配置数据源、字符编码、过滤器和视图解析,以及MyBatis的整合和事务管理。
摘要由CSDN通过智能技术生成

SSM整合

在这里插入图片描述
1.web.xml

  1. 字节编码格式
  2. 代理servlet
  3. session过期时间
<?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">
    <!--DispatcherServlet-->
    <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:applicationContext.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>

    <!--encodingFilter过滤器-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    </web-app>

2.对应的依赖

<?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.wei</groupId>
    <artifactId>ssmbuild</artifactId>
    <version>1.0-SNAPSHOT</version>
<!--    mybatis-spring  jsp jstl-->
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
<!--    spring与mybatis整合-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>
</dependencies>
<!--    静态资源导出依赖Java resource下的导出-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes> <include>**/*.properties</include>
                    <include>**/*.xml</include> </includes>
                <filtering>false</filtering> </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes> <include>**/*.properties</include>
                    <include>**/*.xml</include> </includes>
                <filtering>false</filtering> </resource>
        </resources>
    </build>
</project>

3.对应的配置文件
spring-dao.xml

  1. 获取数据源,整合mybatis
  2. 创建会话对象
<?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"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/context
     https://www.springframework.org/schema/context/spring-context.xsd">

  <!-- 配置整合mybatis -->
  <!-- 1.关联数据库文件 -->
  <context:property-placeholder location="classpath:database.properties"/>
<!--大的组件容器  -->
  <!-- 2.数据库连接池 -->
  <!--数据库连接池
      dbcp 半自动化操作 不能自动连接
      c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
      hikari springboot2.0内置  druid
  -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
      <!-- 配置连接池属性 -->
      <property name="jdbcUrl" value="${jdbc.url}"/>
      <property name="driverClass" value="${jdbc.driver}"/>
      <property name="user" value="${jdbc.username}"/>
      <property name="password" value="${jdbc.password}"/>

      <!-- c3p0连接池的私有属性 -->
      <property name="maxPoolSize" value="30"/>
      <property name="minPoolSize" value="10"/>
      <!-- 关闭连接后不自动commit -->
      <property name="autoCommitOnClose" value="false"/>
      <!-- 获取连接超时时间 -->
      <property name="checkoutTimeout" value="10000"/>
      <!-- 当获取连接失败重试次数 -->
      <property name="acquireRetryAttempts" value="2"/>
  </bean>

  <!-- 3.配置SqlSessionFactory对象 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <!-- 注入数据库连接池 -->
      <property name="dataSource" ref="dataSource"/>
      <!-- 配置MyBaties全局配置文件:mybatis-config.xml 指定mapper的配置文件的位置-->
      <property name="configLocation" value="classpath:mybatis-config.xml"/>
  </bean>

  <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 sqlSessionimpl  自动实现实现类因为spring当中自动创建sqlsession是没有set方法-->
<!--    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
<!--        &lt;!&ndash; 注入sqlSessionFactory &ndash;&gt;-->
<!--        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
<!--        &lt;!&ndash; 给出需要扫描Dao接口包 &ndash;&gt;-->
<!--        <property name="basePackage" value="com.wei.dao"/>-->
<!--    </bean>-->
<!--    扫描自定义的mapper接口-->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <property name="basePackage" value="com.wei.dao"/>
      <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  </bean>


spring-service.xml

  1. 数据源的引用,将dao层注入到spring总容器当中
  2. 将对应的mapper组件注册Bean
<?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"
       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">
<!--整合service-->
<!-- 扫描service相关的bean -->
<context:component-scan base-package="com.wei.service" />



<!--    &lt;!&ndash;BookServiceImpl注入到IOC容器中 托管对应的组件&ndash;&gt;-->
<bean id="BookServiceImpll" class="com.wei.service.BookServiceImpll">
    <property name="bookMapper" ref="bookMapper"/>
</bean>

<bean id="BookServiceImpll2" class="com.wei.service.BookServiceImpll">
    <property name="bookMapper" ref="bookMapper"/>
</bean>

<!-- 配置事务管理器,声明式事物 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入数据库连接池 数据源-->
    <property name="dataSource" ref="dataSource" />
</bean>
<!--aop横切事物支持-->
</beans>

数据源的注入:
数据源的注入
spring-mvc:

  1. 对应的视图转换器
  2. 组件扫描
<?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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--    开启注解事物-->
    <mvc:annotation-driven/>
<!--    静态默认servlet配置-->
    <mvc:default-servlet-handler/>
<!--    视图解析器  id 是一个标识-->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
               id="internalResourceViewResolver">
    <!-- 前缀 -->
    <property name="prefix" value="/WEB-INF/jsp/" />
    <!-- 后缀 -->
    <property name="suffix" value=".jsp" />
</bean>
<!--扫描的对应的包-->
    <context:component-scan base-package="com.wei.controller"/>
</beans>

4.对应的组件总容器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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--spring核心配置文件 整合的容器-->
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

5.具体的业务实现
在这里插入图片描述
dao:具体的sql执行

public interface BookMapper {
    //增加一个Book
    int addBook(Books book);

    //根据id删除一个Book
    int deleteBookById(int BookId);

    //更新Book
    int updateBook(Books books);

    //根据id查询,返回一个Book
    Books queryBookById(int id);

    //查询全部Book,返回list集合
    List<Books> queryAllBook();
    //    查询对应的部分数据
}

dao.xml (mybatis层)

<?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.wei.dao.BookMapper">
<!--    绑定接口-->
<!--    查询所有的书籍-->
    <select id="queryAllBook" resultType="Books">
--         select*from books where bookID=1
    select*from books
    </select>

<!--    根据id删除一个数据-->
    <delete id="deleteBookById" parameterType="int">-- 自动转换为integer
        delete from books
        where bookID=#{bookID}
    </delete>

<!--    根据id查询-->
    <select id="queryBookById" resultType="Books">
        select *from books
        where bookID=#{bookID};
    </select>

<!--    根据id增加  参数类型-->
    <insert id="addBook" parameterType="Books">
<!--主键不用自己写,已经是自增,但是需要一一对应写前面的字段-->
        insert into books(bookName, bookCounts, detail)
        values(#{bookName},#{bookCounts},#{detail});
    </insert>

<!--    根据id更新-->
    <update id="updateBook" parameterType="Books">
        update books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}
    </update>

</mapper>

service层:调用dao层方法实现对mybatis组件的实现

public interface BookService {
    //增加一个Book
    int addBook(Books book);

    //根据id删除一个Book
    int deleteBookById(int id);

    //更新Book
    int updateBook(Books books);

    //根据id查询,返回一个Book
    Books queryBookById(int id);

    //查询全部Book,返回list集合
    List<Books> queryAllBook();
}

service.xml

public class BookServiceImpll implements BookService {
    @Autowired
    private BookMapper bookMapper;

    //调用上一层的接口这里面的引入的接口和增加定义的接口转换,spring事物的介入
    public void setBookMapper(BookMapper BookMapper) {
        this.bookMapper = BookMapper;
    }

    public int addBook(Books book) {
        return bookMapper.addBook(book);
    }

    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

controller层的实现:

@Controller
@RequestMapping("/Demo")
public class bookController {
    @Autowired
    @Qualifier("BookServiceImpll")//指定对应的组件id
    private BookService BookService;
    @RequestMapping("/allBook")
    public String list(Model model) {
    List<Books> list = BookService.queryAllBook();
    model.addAttribute("list", list);
    return "allBook";
   }
//   @RequestMapping("/addBook")
//    public String addBook(Model model){
//       Books books = new Books();
//       int i = BookService.addBook(new Books(6,"jieke",258,"车德强"));
//        model.addAttribute("addBook",books);
//        return "allBook";
//   }
//  对应的增加按钮首页
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println(books);
        BookService.addBook(books);
        return "redirect:/Demo/allBook";

    }
   @RequestMapping("/deleteBooks")
    public String deleteBooks(@RequestParam("BookId") int BookId){
       BookService.deleteBookById(BookId);

       return "allBook";

   }
//对应的首页的按钮
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
    Books books = BookService.queryBookById(id);
    System.out.println(books);
    model.addAttribute("book",books );
    return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Model model, Books book) {
    System.out.println(book);
    BookService.updateBook(book);
    Books books = BookService.queryBookById(book.getBookID());
    model.addAttribute("books", books);
    return "redirect:/Demo/allBook";
    }

    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
     BookService.deleteBookById(id);
//     重定向到对应的页面
    return "redirect:/Demo/allBook";
    }
}

这一层与对应的spring-service绑定进行视图的跳转以及具体方法的调用。

对应的jsp页面:
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
  <title>首页</title>
  <style type="text/css">
    a {
      text-decoration: none;
      color: black;
      font-size: 18px;
    }
    h3 {
      width: 180px;
      height: 38px;
      margin: 100px auto;
      text-align: center;
      line-height: 38px;
      background: deepskyblue;
      border-radius: 4px;
    }
  </style>
</head>
<body>

<h3>
  <a href="${pageContext.request.contextPath}/Demo/allBook">点击进入列表页</a>
</h3>
</body>
</html>

addBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
       <title>新增书籍</title>
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <!-- 引入 Bootstrap -->
       <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
       <div class="row clearfix">
           <div class="col-md-12 column">
               <div class="page-header">
                   <h1>
                       <small>新增书籍</small>
                   </h1>
               </div>
           </div>
       </div>
       <form action="${pageContext.request.contextPath}/Demo/addBook" method="post">
           书籍名称:<input type="text" name="bookName"><br><br><br>
           书籍数量:<input type="text" name="bookCounts"><br><br><br>
           书籍详情:<input type="text" name="detail"><br><br><br>
           <input type="submit" value="添加">
       </form>
</div>

updateBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
       <title>修改信息</title>
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <!-- 引入 Bootstrap -->
       <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
       <div class="row clearfix">
           <div class="col-md-12 column">
               <div class="page-header">
                   <h1>
                       <small>修改信息</small>
                   </h1>
               </div>
           </div>
       </div>
       <form action="${pageContext.request.contextPath}/Demo/updateBook" method="post">
           <input type="hidden" name="bookID" value="${book.getBookID()}"/>
           书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/>
           书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
           书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/>
           <input type="submit" value="提交"/>
       </form>
</div>

allBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
       <title>书籍列表</title>
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <!-- 引入 Bootstrap -->
       <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">
       <div class="row clearfix">
           <div class="col-md-12 column">
               <div class="page-header">
                   <h1>
                       <small>书籍列表 —— 显示所有书籍</small>
                   </h1>
               </div>
           </div>
       </div>
       <div class="row">
           <div class="col-md-4 column">
               <a class="btn btn-primary" href="${pageContext.request.contextPath}/Demo/toAddBook">新增</a>
           </div>
       </div>
       <div class="row clearfix">
           <div class="col-md-12 column">
               <table class="table table-hover table-striped">
                   <thead>
               <tr>
                       <th>书籍编号</th>
                       <th>书籍名字</th>
                       <th>书籍数量</th>
                       <th>书籍详情</th>
                       <th>操作</th>
                   </tr>
               </thead>
                   <tbody>
               <c:forEach var="book" items="${requestScope.get('list')}">
                       <tr>
                           <td>${book.getBookID()}</td>
                           <td>${book.getBookName()}</td>
                           <td>${book.getBookCounts()}</td>
                           <td>${book.getDetail()}</td>
                           <td>
<%--    跳转到controller层的对应的方法--%>
                               <a href="${pageContext.request.contextPath}/Demo/toUpdateBook?id=${book.getBookID()}">更改</a> |
                               <a href="${pageContext.request.contextPath}/Demo/del/${book.getBookID()}">删除</a>
                           </td>
                       </tr>
                   </c:forEach>
               </tbody>
               </table>
           </div>
       </div>
</div>

实现:用bootstrap实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值