SSM框架整合详细教程(IDEA版含源码以及所需的配置文件)

1、首先创建一个普通的Maven的项目

2、配置pom.xml,导入依赖(包含所需的jar包和静态资源导出:让.xml和resource下的东西导出)

        依赖:junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring,Lombok

<?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.rk</groupId>
    <artifactId>SSM框架整合</artifactId>
    <version>1.0-SNAPSHOT</version>

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

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

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

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

         <!--Lombok偷懒专用插件,实体类不用写get,set,toString和构造方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
    </dependencies>

    <!--Maven静态资源导出-->
    <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、建立基本结构和配置框架 

  • com.rk.pojo       

  •  com.rk.dao

  • com.rk.service

  • com.rk.controller

  • com.rk.fliter

  • com.rk.utils

  • 在resources下创mybatis-config.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>
    
    </configuration>
  • 在resources下创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">
    
    </beans>
  • 完成后的包结构: 

4、Mybatis层编写及相关配置

        4.1、在数据库配置文件 database.properties

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

        jdbc.url=jdbc:第一个参数安全连接:useSSL=true

                             第二个参数设置编码:useUnicode=true&characterEncoding=utf8

        如果使用的是MySQL8.0+,在jdbc.url=jdbc:增加一个配置时区的参数:

                               & serverTimezone=Asia/Shanghai

        4.2、编写Mybatis的核心配置文件

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

    <!--配置数据源,交给Spring去做-->
    <typeAliases>
        <package name="com.rk.pojo"/>
    </typeAliases>
    
    <mappers>
        <mapper resource="com/rk/dao/BookMapper.xml"/>
    </mappers>

</configuration>

        4.3、在pojo包下创建实体类Books              

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data//get,set,toString方法不用写   
@AllArgsConstructor//有参构造
@NoArgsConstructor//无参构造
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

                其属性名要和数据中表的列相同

        4.4、创建一个持久层接口BookMapper

package com.rk.dao;

import com.rk.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;


public interface BookMapper {
    //增加一本书
    int addBook(Books books);

    //删除一本书
    int deleteBookById(@Param("bookId") int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(@Param("bookId") int id);

    //查询全部的书
    List<Books> queryAllBook();
}

       4. 5、创建对应的配置文件BookMapper.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.rk.dao.BookMapper"><!--绑定接口-->

           <!--增加一个Book-->
    <insert id="addBook" parameterType="Books">
        insert into rk.books (bookName,bookCounts,detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>
            
            <!--根据id删除一个Book-->
    <delete id="deleteBookById" parameterType="int">
        delete from rk.books
        where bookID=#{bookId}
    </delete>

             <!--更新Book-->
    <update id="updateBook" parameterType="Books">
        update rk.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookID};
    </update>
    
            <!--根据id查询,返回一个Book-->
    <select id="queryBookById" resultType="Books">
        select * from rk.books
        where bookID=#{bookId};
    </select>
            <!--查询全部Book-->
    <select id="queryAllBook" resultType="Books">
        select * from rk.books;
    </select>

</mapper>

        4.6、编写Service层的接口和实现类

                BookService

package com.rk.service;

import com.rk.pojo.Books;
import java.util.List;
public interface BookService {

    //增加一本书
    int addBook(Books books);

    //删除一本书
    int deleteBookById(int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(int id);

    //查询全部的书
    List<Books> queryAllBook();
}

                BookServiceImpl

package com.rk.service.Impl;

import com.rk.dao.BookMapper;
import com.rk.pojo.Books;
import com.rk.service.BookService;
import java.util.List;
public class BookServiceImpl implements BookService {
    //业务层调用dao层,组合dao层
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

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

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

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

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

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

5、Spring层编写

        5.1整合Mybatis层,编写Spring-dao.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"
       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:database.properties"/>

    <!--2、连接池  id必须为dataSource
            dbcp(半自动化操作,不能自动连接)、c3p0(自动化操作,并且可以自动设置到对象中)、druid -->
    <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}"/>


        <!-- 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"/>
            <!--绑定Mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>


    <!--4、配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--要扫描的包-->
        <property name="basePackage" value="com.rk.dao"/>
    </bean>

</beans>

        5.2、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"
       xmlns:contxt="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、扫描serviece下的包-->
    <contxt:component-scan base-package="com.rk.service"/>

    <!--2、将我们所有的业务类,注入到Spring,可以通过配置或者注解实现-->
    <bean id="BookServiceImpl" class="com.rk.service.Impl.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!--3、声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--4、aop事务支持-->


</beans>

        注意: 所有的Spring.xml文件必须要关联在同一个上下文(context)中,这样所有关联在一起的注册类都可以相互引用,例如上面的bookMapper

6、SpringMVC层的编写

        6.1增加Web支持

        6.2、在resource下创建一个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、注解驱动-->
    <mvc:annotation-driven/>
    <!--2、静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--3、扫描包:controller-->
    <context:component-scan base-package="com.rk.controller"/>
    <!--4、视图解析器-->
   <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>

</beans>

        6.3、编写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">
    <!--1、DispatchServlet-->
    <servlet>
        <servlet-name>DispatchServlet</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>DispatchServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--2、乱码过滤-->
    <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>

    <!--3、配置Session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

</web-app>

        6.4、在applicationContext中引入spring-dao.xml、spring-servlet.xml、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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>

</beans>

7、Controller 和 视图层编写 

        7.1、查询书籍

        Controller

package com.rk.controller;
import com.rk.pojo.Books;
import com.rk.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    //controller调service层

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部的书籍,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("list",books);
        return "allBook";
    }
}

        书籍列表页面 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>
    <!-- 引入 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">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/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>
                </tr>
                </thead>
                <tbody>
                <C:forEach var="book" items="${list}">
                    <tr>
                        <td>${book.bookID}</td>
                        <td>${book.bookName}</td>
                        <td>${book.bookCounts}</td>
                        <td>${book.detail}</td>
                    </tr>
                </C:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

         7.2、新增书籍

          Controller

//跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books){

        int i = bookService.addBook(books);
        return "redirect:/book/allBook";//重定向到allBook请求
    }

        因为当书籍在数据库增加时,要重新发起请求,才能在allBook页面显示

        增加页面:addBook.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加书籍</title>
    <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 method="post" action="${pageContext.request.contextPath}/book/addBook">
        <div class="form-group">
            <label>书籍名称:</label>
            <input type="text" name="bookName" class="form-control" required>
        </div>

        <div class="form-group">
            <label>书籍数量:</label>
            <input type="text" name="bookCounts" class="form-control" required>
        </div>

        <div class="form-group">
            <label>书籍描述:</label>
            <input type="text" name="detail" class="form-control" required>
        </div>

        <div class="form-group">
        <input type="submit" class="form-control" value="添加">
        </div>
    </form>

</div>
</body>
</html>

        7.3修改和删除书籍

        Controller

   //跳转到修改书籍页面     并且要携带一本书籍的信息
    @RequestMapping("/toUpdateBook")
    public String toUpdatePaper(int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("Qbooks",books);
        return "updateBook";
    }

    
    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books)
    {
        int i = bookService.updateBook(books);
        return "redirect:/book/allBook";//重定向到allBook请求
    }

    //删除书籍
    @RequestMapping("/deleteBook")
    public String deleteBook(int id)
    {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";//重定向到allBook请求
    }

        updateBook.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍</title>
    <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 method="post" action="${pageContext.request.contextPath}/book/updateBook">
        <input type="hidden" name="bookID" value="${Qbooks.bookID}"/>
        <div class="form-group">
            <label>书籍名称:</label>
            <input type="text" name="bookName" class="form-control" value="${Qbooks.bookName}" required>
        </div>

        <div class="form-group">
            <label>书籍数量:</label>
            <input type="text" name="bookCounts" class="form-control" value="${Qbooks.bookCounts}" required>
        </div>

        <div class="form-group">
            <label>书籍描述:</label>
            <input type="text" name="detail" class="form-control" value="${Qbooks.detail}" required>
        </div>

        <div class="form-group">
        <input type="submit" class="form-control" value="修改">
        </div>
    </form>

</div>
</body>
</html>

        7.4、查询功能

        从bookMapper层开始  

//通过书名查询一本书
    Books queryBookByName(@Param("bookName") String name);

        bookMapper.xml

 <select id="queryBookByName" resultType="Books">
        select * from rk.books where bookName= #{bookName}
    </select>

        BookServiceImpl

  public Books queryBookByName(String name) {
        return bookMapper.queryBookByName(name);
    }

        controller

  //查询
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName, Model model)
    {
        Books books = bookService.queryBookByName(queryBookName);
        if(books==null)
            return "redirect:/book/allBook";

        List<Books> list=new ArrayList<Books>();
        list.add(books);
        System.out.println(books);
        model.addAttribute("list",list);
        return "allBook";
    }

        框架搭建完成后,如果要增加功能,要从底层一层一层往上写        

         

         

猜你喜欢

转载自blog.csdn.net/m0_46979453/article/details/120571685