ssm整合流程

文章目录

环境搭建

  1. 不勾选模板创建一个maven项目。
    ssm整合流程

  2. 导入依赖

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

3.静态资源过滤

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

4.建立各级目录及配置文件
ssm整合流程

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>

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>

文件上方出现提示点击create new application context
ssm整合流程

ssm整合流程

连接数据库

1.创建数据库配置文件
ssm整合流程

database.properties

driver=com.mysql.cj.jdbc.Driver
#mybtis8.0及以上版本需要加时区的设置
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=root

2.连接数据库
ssm整合流程

输入用户名和密码ssm整合流程

选择对应数据库ssm整合流程
配置一下别名
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>
<typeAliases>
    <package name="cn.zjq.pojo"></package>
</typeAliases>
</configuration>

创建实体类

Books

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
    int bookID;
    String bookName;
    int bookCounts;
    String detail;
}

编写Dao层

编写mapper接口

import cn.zjq.pojo.Books;

import java.util.List;

public interface BookMapper {
    Books selectBooksById(int id);
    List<Books> selectAll();
    int insertBooks(Books books);
    int deleteBooks(int id);
    int updateBooks(Books books);
}

编写xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.zjq.dao.BookMapper">
    <select id="selectBooksById" resultType="Books">
        select
       bookName,
       bookID,
       detail,
       bookCounts
       from books where bookID = #{id}

    </select>
    <select id="selectAll" resultType="Books">
          select
       bookName,
       bookID,
       detail,
       bookCounts
       from books
    </select>
    <insert id="insertBooks" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
         VALUES (#{bookName},#{bookCounts},#{detail})
    </insert>
    <delete id="deleteBooks">
        DELETE from ssmbuild.books where bookID = #{id}
    </delete>
    <update id="updateBooks" parameterType="Books">
        update ssmbuild.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID = #{bookID}
    </update>
</mapper>

测试DAO操作数据库是否正常

为了测试方便我们需要一个MybatisUtils


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//sqlSession->sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    //把SqlSessionFactory作为成员变量注入工具类
    static{
        try {//利用静态代码块获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//创建SqlSessionFactoryBuilder来获取SqlSessionFactory
            //通过读取配置文件获取SqlSessionFactory
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static SqlSession getSqlSession(){
        //获取sqlSession对象
        return  sqlSessionFactory.openSession();

    }
}

同时mybatis-config.xml需要增加一些设置用于测试

    <!--测试使用数据-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--每一个mybatis.xml文件都必须注册!!-->
        <mapper resource="cn/zjq/dao/BookMapper.xml"/>
    </mappers>

编写测试类:这里需要注意mybatis默认是不提交事务的,注意增删改操作完毕之后没有报错但是数据库没有改,这个时候我们需要使用sqlSession.commit();手动提交事务,或者在创建sqlSession的时候定义sqlSessionFactory.openSession(true)即设置自动提交事务。

         //获取sqlSession
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行sql
        //获取mapper
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
//        由mapper执行sql
        Books books = new Books();
        books.setBookCounts(12);
        books.setBookName("BOOK");
        books.setDetail("dloal");
        int i = mapper.deleteBooks(13);
        System.out.println(i);
        sqlSession.commit();
        //关闭sqlSession
        sqlSession.close();
    }

测试成功
ssm整合流程

编写Service层

BookService

import java.util.List;

public interface BookService {
    Books selectBooksById(int id);
    List<Books> selectAll();
    int insertBooks(Books books);
    int deleteBooks(int id);
    int updateBooks(Books books);
}

BookServiceImpl

package cn.zjq.service;

import cn.zjq.dao.BookMapper;
import cn.zjq.pojo.Books;


import java.util.List;

public class BookServiceImpl implements BookService {
    //嵌入dao
    private BookMapper bookMapper;
    public Books selectBooksById(int id) {
        return bookMapper.selectBooksById(id);
    }

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

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

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

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

整合Spring

dao层整合

1.关联数据库配置文件
2.连接池
3.sqlSessionFactory
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">
    <!--关联数据库配置文件-->
    <context:property-placeholder location="database.properties"/>
    <!--连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${url}"/>
        <property name="password" value="${password}"/>
        <property name="driverClass" value="${driver}"/>
        <property name="user" value="${username}"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configuration" value="classpath:mybatis-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置动态扫描dao包下的接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.zjq.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
     </bean>
</beans>

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: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">
    <!--扫描service包下的接口-->
    <context:component-scan base-package="cn.zjq.service"/>
    <!--声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--aop-->
    <bean 
</beans>

通过注解将业务层接口注入spring容器

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;
@Data
@Service
public class BookServiceImpl implements BookService {
    //嵌入dao
    @Autowired
    private BookMapper bookMapper;
    public Books selectBooksById(int id) {
        return bookMapper.selectBooksById(id);
    }

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

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

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

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

增加web支持

ssm整合流程
选中web application
ssm整合流程
编写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.注册DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-mvc.xml</param-value>
            </init-param>
            <!--启动级别-1-->
            <load-on-startup>1</load-on-startup>
        </servlet>
            <!--/ 匹配所有的请求;(不包括.jsp)-->
            <!--/* 匹配所有的请求;(包括.jsp)-->
        <servlet-mapping>
                <servlet-name>springmvc</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>

</web-app>

编写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:mvc="http://www.springframework.org/schema/mvc"
       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
       http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
    <!--注解驱动-->
   <mvc:annotation-driven/>
    <!--扫描包-->
    <context:component-scan base-package="cn.zjq.controller"/>
    <!--处理器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!--适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <!--视图解析器:DispatcherServlet给他的ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>
 

添加前端页面:前端页面的路径要和自己配置的视图解析器路径一致。

<%--
  Created by IntelliJ IDEA.
  User: 957
  Date: 2021/9/20
  Time: 15:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

完成到这一步我们就可以开始写
第一个controller了
helloworld走一波!


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class HelloController  {
@RequestMapping("/hello")
    public String HELLO(Model model )  {
        model.addAttribute("msg","hello");
        return "hello";
    }
}

ssm整合流程
好了到这里基本的ssm整合就已经完成了

访问出现404的解决办法

ssm整合流程

查看WB-INF目录下是否存在lib目录,如果没有手动创建一个并把包导进去。

上一篇:codeforces1481 E. Sorting Books(贪心+dp)


下一篇:DRF框架(十)——drf框架里面,除了默认的增删改查,其他的一些自定义的动作,如何用代码实现