SSM项目整合-完整流程一览

SSM完整笔记

  • Mybatis-01-配置详解
  • Mybatis-02-日志,注解和分页,一对多,多对一,缓存
  • Spring详解-01-依赖注入等方式
  • Spring详解-02-注解,面向切面编程等
  • Spring详解-03-整合Mybatis,事务配置
  • SpringMVC-01-第一个SpringMVC程序,注解开发,Restful风格
  • SpringMVC-02-Ajax,拦截器,文件上传下载
  • SSM项目整合-完整流程一览
  • 笔记相关代码:https://gitee.com/chelsea_h/ssm-integration

官网文档

  • Spring文档:https://docs.spring.io/spring-framework/docs/5.2.9.RELEASE/spring-framework-reference/core.html#spring-core
  • Mybatis文档:http://www.mybatis.org/mybatis-3/zh/index.html
  • SpringMVC文档:https://docs.spring.io/spring-framework/docs/current/reference/html/web.html

一:前期准备

1. 创建数据库
CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books`  (
  `bookID` int(11) NOT NULL AUTO_INCREMENT COMMENT '书id',
  `bookName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '书名',
  `bookCounts` int(11) NOT NULL COMMENT '数量',
  `detail` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '描述',
  INDEX `bookID`(`bookID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8;

INSERT INTO `books` VALUES (1, 'Java', 11, '从入门到放弃');
INSERT INTO `books` VALUES (2, 'MySQL', 10, '从删库到跑路');
INSERT INTO `books` VALUES (3, 'Linux', 5, '从进门到进牢');
2. 创建maven项目,添加web支持,导入相关依赖(根据自己项目需求进行增删

<dependencies>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>5.3.8version>
    dependency>

    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
        <scope>testscope>
    dependency>

    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.46version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.2version>
    dependency>

    
    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.20version>
        <scope>providedscope>
    dependency>


    
    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>javax.servlet-apiartifactId>
        <version>4.0.1version>
        <scope>providedscope>
    dependency>

    
    <dependency>
        <groupId>javax.servlet.jspgroupId>
        <artifactId>jsp-apiartifactId>
        <version>2.2.1-b03version>
        <scope>providedscope>
    dependency>

    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>jstlartifactId>
        <version>1.2version>
    dependency>

    <dependency>
        <groupId>com.mchangegroupId>
        <artifactId>c3p0artifactId>
        <version>0.9.5.5version>
    dependency>

    
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.9.7version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>2.0.6version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.3.8version>
    dependency>

dependencies>
3. maven配置静态资源过滤


<build>
    <resources>
        <resource>
            <directory>src/main/resourcesdirectory>
            <includes>
                <include>**/*.propertiesinclude>
                <include>**/*.xmlinclude>
            includes>
            <filtering>truefiltering>
        resource>
        <resource>
            <directory>src/main/javadirectory>
            <includes>
                <include>**/*.propertiesinclude>
                <include>**/*.xmlinclude>
            includes>
            <filtering>truefiltering>
        resource>
    resources>
build>

二:Mybatis层

1. 编写db.properties文件,存放数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
# 如果使用的是Mysql8.0以上,就得加上时区设置
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.username=chelsea
jdbc.password=********
2. 编写Mybatis-config.xml文件
  • 由于最后要和Spring整合,一切基于bean的思想,所以数据源没在这块配置,放入了spring配置文件。下面的这些配置一般也可以放在spring文件中进行属性设置,但项目一般八setting和别名和映射放入原配置文件中,结构更清晰。
  • 注:此处日志使用log4j,对于此方式可参考
    Mybatis-02-日志,注解和分页,多对一,一对多,缓存

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    settings>

    <typeAliases>
        <package name="com.chelsea.pojo"/>
    typeAliases>

    <mappers>
        <mapper resource="com/chelsea/mapper/BookMapper.xml"/>
    mappers>

configuration>
3. 编写实体类(省略)
4. 编写Mapper接口和xml文件(xml记得在mybatis-config.xml文件中进行映射)
public interface BookMapper {

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

    /*删除一本书*/
    int deleteBookById(@Param("bookID") int bookID);

    /*修改一本书*/
    int updateBook(Books books);

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

    /*查询所有书*/
    List<Books> queryAllBook();

    /*查询书籍*/
    List<Books> queryBooks(@Param("queryInfo") String queryInfo);
}

<mapper namespace="com.chelsea.mapper.BookMapper">

     
    <insert id="addBook" parameterType="Books">
        insert into books (bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})
    insert>

    
    <delete id="deleteBookById" parameterType="_int">
        delete from books where bookID = #{bookID}
    delete>

    
    <update id="updateBook" parameterType="Books">
        update books set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID = #{bookID}
    update>

    
    <select id="queryBookById" parameterType="_int" resultType="Books">
        select * from books where bookID = #{bookID}
    select>

    
    <select id="queryAllBook" resultType="Books">
        select * from books
    select>

    
    <select id="queryBooks" resultType="Books" parameterType="String">
        select * from books where bookName like "%"#{queryInfo}"%"
    select>

mapper>
5. 编写Service层
  • service层是控制层需要调用的服务,其实就是根据业务需求封装一下dao层,示例如下:(Service层接口在这省略)
public class BookServiceImpl implements BookService {

    /*service层要调用mapper层,所以要组合进来*/
    private BookMapper bookMapper;
	//set方法为了自动注入
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

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

    @Override
    public int deleteBookById(int bookID) {
        return bookMapper.deleteBookById(bookID);
    }

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

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

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

    @Override
    public List<Books> queryBooks(String queryInfo) {
        return bookMapper.queryBooks(queryInfo);
    }

}

三:Spring整合Mybatis

1. 以Spring bean的方式写Mybatis配置
  • 此处数据源使用c3p0(记得导入相关依赖)

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <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}"/>

        
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        
        <property name="autoCommitOnClose" value="false"/>
        
        <property name="checkoutTimeout" value="10000"/>
        
        <property name="acquireRetryAttempts" value="2"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        
        <property name="basePackage" value="com.chelsea.mapper"/>
    bean>

beans>
2. spring整合service层(就是将类配置为bean,并且属性自动配置)

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://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 https://www.springframework.org/schema/aop/spring-aop.xsd">

    
    <context:component-scan base-package="com.chelsea.service"/>

    
    <bean id="BookServiceImpl" class="com.chelsea.service.BookServiceImpl">
        
        <property name="bookMapper" ref="bookMapper"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource"/>
    bean>

    

    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        tx:attributes>
    tx:advice>

    
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.chelsea.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    aop:config>

beans>

四:Spring整合SpringMVC

1. 在web.xml中配置DispatcherServlet等

<servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
        <param-name>contextConfigLocationparam-name>
        
        <param-value>classpath:applicationContext.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
servlet-mapping>


<filter>
    <filter-name>encodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
        <param-name>encodingparam-name>
        <param-value>utf-8param-value>
    init-param>
filter>
<filter-mapping>
    <filter-name>encodingFilterfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>


<session-config>
    <session-timeout>15session-timeout>
session-config>
2. 编写spring-mvc.xml配置文件
  • 常规操作

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>

    
    <mvc:annotation-driven/>

    
    <context:component-scan base-package="com.chelsea.controller"/>

    
    <mvc:default-servlet-handler/>

beans>

3. 编写一个总的spring文件(applicationContext.xml),将前面的所有spring文件整合起来

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

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

beans>
4. 至此整合完毕

五:编写Controller

  • 只展示部分功能作为示例即可,完整代码可访问gitee
@Controller
@RequestMapping("/book")
public class BookController {

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

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

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

    /*添加书籍的请求*/
    @RequestMapping(value = "/addBook",method = RequestMethod.GET)
    public String addBook(Books books){
        System.out.println(books);
        bookService.addBook(books);
        /*重定向到allBook*/
        return "redirect:/book/allBook";
    }

    /*跳转到修改页面*/
    @RequestMapping("/toUpdate")
    public String toUpdate(@Param("id") int id, Model model){
        System.out.println("update id is : "+id);
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "updateBook";
    }

    /*修改数据*/
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        System.out.println("修改书籍:"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    /*删除数据*/
    @RequestMapping("/deleteBook/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    /*查询书籍,使用like语句进行模糊查询,如果为空则会返回所有数据*/
    @RequestMapping("/queryBook")
    public String queryBook(String queryInfo,Model model){
        /*如果为空会默认显示全部数据*/
        List<Books> queryList = bookService.queryBooks(queryInfo);
        //未查到信息:这种情况不存在
        if(queryList.size()==0){
            queryList = bookService.queryAllBook();
            model.addAttribute("error","未查到书籍信息");
        }
        model.addAttribute("bookList",queryList);
        return "allBook";
    }

}

六:编写前端

  • 同样只展示部分,完整代码参考gitee
<html>
<head>
    <title>Titletitle>
    <%--使用bootstrap CDN--%>
    <link href="https://cdn.staticfile.org/twitter-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 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-8 column">
                <%--查询书籍--%>
                <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="get" style="float: right">
                    <span style="color: red;font-weight: bold">${error}span>
                    <input type="text" placeholder="查询书籍" class="form-control" name="queryInfo">
                    <input type="submit" value="查询" class="btn btn-primary">
                form>
            div>
        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>
                <%--从list中遍历数据--%>
                <tbody>
                    <c:forEach var="book" items="${bookList}">
                        <tr>
                            <td>${book.bookID}td>
                            <td>${book.bookName}td>
                            <td>${book.bookCounts}td>
                            <td>${book.detail}td>
                            <td>
                                <a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改a>
                                 | 
                                <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除a>
                            td>
                        tr>
                    c:forEach>
                tbody>
            table>
        div>
    div>

div>

body>
html>
  • 至此SSM已完成所有整合,路漫漫其修远兮,吾将上下而求索。

你可能感兴趣的:(JavaEE,spring,mybatis,springmvc)