ssm整合,我的案例

学习过程,B站一位老师的视屏:https://www.bilibili.com/video/av73118229php

博客网址:https://blog.kuangstudy.com/index.php/archives/487/css

我的项目打包:ssm_book  提取码 : oum2html

我的整合思路

最好先保证每一个框架都能独立运行,再去搞整合,这样排错比较容易。java

先展现一下结果mysql

1、先整合一下mybatis和spring

1.导包,一次性所有导完须要的包web

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.0.2.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <mysql.version>5.1.6</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>

    <dependencies>
        <!-- spring -->
        <dependency>
            <!--aop相关的技术-->
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <!--aop的jar包-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--spring的容器-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--web与webmvc是springmvc须要用的jar包-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--单元测试-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--事务-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--jdbc模板技术-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--单元测试-->
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <!--mysql驱动包-->
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <!--servlet-->
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <!--jsp-->
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <!--想在页面也el表达式须要用到的包-->
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
        <dependency>
            <!--mybatis-->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <!--spring整合mybatis须要用到这个包-->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    
  <build>
      <!--maven资源过滤设置-->
      <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>

2.前期mysql准备spring

create database ssm;
use ssm;
create table books(
    bookid int primary key auto_increment not null comment '书id',
  bookName varchar(100) not null comment '书名',
    bookCounts int(11) not null comment '书数量',
    detail varchar(200) not null comment '书描述'
)engine = innodb default charset = utf8

insert into books(bookName,bookCounts,detail)
VALUES
('Java',2,'从入门到放弃'),
('MySql',2,'从删库到跑路'),
('Linux',2,'从进门到进牢');

3.实体类sql

public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
   getter,setter...
}

4.BooksMapper接口和映射文件BooksMapper.xml数据库

BookMapper.java

public interface BooksMapper {
//查询全部
List<Books> queryAllBook();
//根据id查询
Books queryBookById(int id);
//添加
int addBook(Books book);
//修改
int updateBook(Books books);
//删除
int deleteBook(int id);
//模糊查询
List<Books> queryByName(String name);
}
BookMappaer.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.cong.dao.BooksMapper">
<select id="queryAllBook" resultType="books">
select * from ssm.books;
</select>
<select id="queryBookById" resultType="books" parameterType="int">
select * from ssm.books where bookid = #{id};
</select>
<insert id="addBook" parameterType="books">
insert into ssm.books(bookName, bookCounts, detail)
VALUES (#{bookName},#{bookCounts},#{detail});
</insert>
<update id="updateBook" parameterType="books">
update ssm.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookid = #{bookID};
</update>
<delete id="deleteBook" parameterType="int">
delete from ssm.books where bookid = #{bookId}
</delete>
<select id="queryByName" resultType="books" parameterType="string">
select * from ssm.books where bookName like #{name};
</select>
</mapper>

5. mybatis核心配置文件mybatis-config.xmlbootstrap

<?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>
    <!--log4j-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--别名-->
    <typeAliases>
        <package name="com.cong.pojo"/>
    </typeAliases>
</configuration>

 6. db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

7. 建立application.xml配置文件,这个主要就是将其它的配置import进来

<?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 ">
    <import resource="spring-service.xml"/>
    <import resource="spring-dao.xml"/>
</beans>

8. 编写spring与mybatis的配置文件spring-dao.xml整合dao层,这里使用的数据源是c3p0

<?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">
    <!--1.关联数据库文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--2.dataSource-->
    <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--3.SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="datasource"/>
        <!-- 绑定mybatis全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!-- 4.扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cong.dao"/>
    </bean>
</beans>

9. spring整合service层,spring-service.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">
    <!--将BooksServiceImpl注入到spring-->
    <bean class="com.cong.service.BooksServiceImpl" id="booksService">
        <property name="booksMapper" ref="booksMapper"/>
    </bean>
    <!--声明式配置事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"/>
    </bean>
    <!--配置事务的通知,本项目不须要-->
</beans>

10. 到了这里,spring整合mybatis就算成功了,先测试一下

测试类

public class SpringTest {
    @Test
    public void test1(){
        //加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取对象
        BooksService booksService = (BooksService) context.getBean("booksService");
        //执行方法
        List<Books> books = booksService.queryAllBook();
        for (Books book : books) {
            System.out.println(book.toString());
        }
    }
}

结果,能够查询

 3、整合springmvc

在这里就不作mvc的测试了,

主要就是配置springmvc.xml和web.xml以后,简单写一个controller和一个简单的jsp页面配合index.jsp,

而后配置好tomcat服务器,启动以后可以作到页面跳转就没问题。

1.springmvc的配置文件spring-mvc.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: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">

    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven />
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>
    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 4.扫描controller -->
    <context:component-scan base-package="com.cong.controller" />
</beans>

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

3.在application中导入全部的配置文件

<?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 ">
    <!--导入其余配置文件-->
    <import resource="spring-mvc.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
</beans>

这里啰嗦一下,在web.xml中,咱们配置了

<param-value>classpath:applicationContext.xml</param-value>

就是将配置文件中包含的全部东西注册到tomcat服务器中,而在applicationContext.xml中引入了其余的配置文件,因此就没有问题

还有另一种引入的方法,就是在web.xml中配置。

通常来讲,web.xml中应该默认配置的是springmvc的配置文件,也就是咱们案例中的spring-mvc.xml

而后将其它的配置文件好比spring的配置文件application.xml(有的人会将mybatis和spring整合到这里面)经过监听器注册到tomcat服务器中

 <!-- 配置Spring的监听器 -->
    <!--该监听器默认状况只能加载在web中配置了的配置文件,好比次案例中的applicationContext.xml-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 因此能够设置额外的配置文件,好比 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </context-param>

4. 编写controller类BookController

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("booksService")
    private BooksService booksService;
    //显示全部书籍
    @RequestMapping("/allBook")
    public String listBooks(Model model){
        List<Books> booksList = booksService.queryAllBook();
        model.addAttribute("list", booksList);
        return "allBook";
    }
    //跳转到添加书籍的页面
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }
    //修改完书籍重定向到全部书籍页面
    @RequestMapping("/addBook")
    public String addPaper(Books books) {
        booksService.addBook(books);
        return "redirect:/book/allBook";
    }
    //跳转到修改书籍页面
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model,int id) {
        Books books = booksService.queryBookById(id);
        model.addAttribute("book",books );
        return "updateBook";
    }
    //修改完书籍重定向到全部书籍页面
    @RequestMapping("/updateBook")
    public String updateBook(Model model, Books book) {
        booksService.updateBook(book);
        return "redirect:/book/allBook";
    }
    //删除书籍直接重定向到全部书籍页面
    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        booksService.deleteBook(id);
        return "redirect:/book/allBook";
    }
    //根据名字模糊查找书籍,跳转到显示查询列表页面
    @RequestMapping("/findByKeyWord")
    public String findByName(Model model,String keyword){
        List<Books> list = booksService.queryByName("%"+keyword+"%");
        model.addAttribute("list", list);
        return "allBook";
    }
}

5.下面是jsp文件

5.1 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}/book/allBook">点击进入列表页</a><br/><br/>
</h3>
</body>
</html>

5.2  书籍页面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}/book/toAddBook">新增</a>
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">返回列表</a>
        </div>
        <div class="col-md-4 column">
            <form action="/book/findByKeyWord" method="post" class="form-inline">
                <input type="text" name="keyword" placeholder="请输入查询的书籍名称" class="form-control">
                <input type="submit" value="查询" class="btn btn-primary" />
            </form>
        </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>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
                            <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

5.3 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}/book/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>
</body>
</html>

5.4 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}/book/updateBook" method="post">
        <input type="hidden" name="bookID" value="${book.getBookID()}"/>
        书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/><br><br><br>
        书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/><br><br><br>
        书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/><br><br><br>
        <input type="submit" value="修改"/>
    </form>
</div>
</body>
</html>

以后,启动tomcat,就能够跑起来了

至此,SSM整合完成

项目结构

相关文章
相关标签/搜索