SSM整合

Posted qtzd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM整合相关的知识,希望对你有一定的参考价值。

搭建整合环境

整合可以有很多种方式,这里用xml+注解的方式

1、环境要求

  • IDEA
  • mysql 5.7.29
  • Tomcat 9.0
  • Maven 3.6.1

2、创建数据库和表

CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;

CREATE TABLE `book` (
  `bookId` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
  `bookName` VARCHAR(100) NOT NULL COMMENT '书名',
  `bookCounts` INT(11) NOT NULL COMMENT '数量',
  `detail` VARCHAR(200) NOT NULL COMMENT '描述',
  KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `book`(`bookId`,`bookName`,`bookCounts`,`detail`)VALUES 
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');

3、创建Maven工程

  • 添加web支持,pom.xml导入相关的依赖
<dependencies>
    <!-- spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>

    <!--lombok依赖-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>

    <!--Junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>    
    
    <!-- druidl连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.21</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- Mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.3</version>
    </dependency>
    
    <!--数据库驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.48</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>
</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>
  • 建立基本结构
com.hui.domain
com.hui.dao
com.hui.service
com.hui.controller
mybatis-config.xml

4、项目中编写实体类

使用lombok快速编写实体类

package com.hui.domain;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {

    private Integer bookId;
    private String bookName;
    private Integer bookCounts;
    private String detail;
}

5、编写dao接口

package com.hui.dao;

import com.hui.domain.Book;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

public interface BookDao {

    List<Book> getAllBook();
}

6、编写service接口和实现类

service接口:

package com.hui.service;

import com.hui.domain.Book;

import java.util.List;

public interface BookService {

    //查询所有书籍
    List<Book> getAllBook();
}

service接口的实现类:

package com.hui.service.impl;

import com.hui.domain.Book;
import com.hui.service.BookService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("bookService")
public class BookServiceImpl implements BookService {

    @Override
    public List<Book> getAllBook() {
        System.out.println("service层:查询所有书籍");
        return null;
    }
}

Spring相关代码及配置文件

  • 创建applicationContext.xml配置文件

在resources资源文件中创建jdbc.properties的配置文件,编写具体的配置信息

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

在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"
       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和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="com.hui" >
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    
    <!-- 关联数据库文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--Spring整合mybatis-->
    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

    </bean>

    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- sql用配置文件写时,要配置mapper映射文件的路径 -->
        <property name="mapperLocations" value="classpath:mapper/*Dao.xml"/>
    </bean>

    <!--配置扫描Dao接口包,动态实现Dao接口注入到spring容器中-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.hui.dao"/>
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

</beans>

在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>
    
    <!--<environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.157.130/ssmbuild?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>-->

    <!--使用的是注解-->
    <mappers>
        <!--<mapper resource="mapper/BookDao.xml"/>--><!--该属性只能在映射配置文件时使用,注解不可用-->
        <package name="com.hui.dao"/><!--不管注解还是配置映射文件,都是最便捷且通用-->
    </mappers>

</configuration>

SpringMVC框架代码编写配置

  • web.xml中配置DispatcherServlet前端控制器

启动Tomcat之后试想一下,在web.xml中配置有前端控制器,web容器会帮我们加载spring-mvc.xml配置文件,在spring-mvc.xml配置文件中我们配置情况是只扫描controller,别的不扫,而applicationContext.xml文件就从头到尾没有执行过,spring中的配置扫描自然也不会去扫描,就相当于没有将spring交到IOC容器当中去,所以,现在的解决方案就是,在启动服务器时就加载spring配置文件,怎么实现呢?这时候监听器listener就派上用场

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

    <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--设置配置文件的路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>


    <!--配置前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载springmvc.xml配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!--启动服务器,创建该servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--解决中文乱码的过滤器-->
    <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>

    <!--开启注解扫描,只扫描Controller注解-->
    <context:component-scan base-package="com.hui">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置的视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--过滤静态资源-->
<!--    <mvc:resources location="/css" mapping="/css/**"/>-->
<!--    <mvc:resources location="/images/" mapping="/images/**"/>-->
<!--    <mvc:resources location="/js/" mapping="/js/**"/>-->


</beans>
  • 创建jsp页面,编写controller

编写index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="store/getAllBook">测试SpringMVC查询</a>
  </body>
</html>

在controller层中的BookController的class类中编写代码

package com.hui.controller;

import com.hui.domain.Book;
import com.hui.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("store/getAllBook")
    public String getAllBook(Model model){

        System.out.println("controller层:查询所有书籍");

        List<Book> list = bookService.getAllBook();
        model.addAttribute("list",list);

        return "list";//在视图解析器中配置了前缀后缀
    }
}

这时候就要创建controller跳转的list.jsp页面了:

/WEB-INF/pages/list.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</title>
</head>
<body>
<h2>查询所有的书籍</h2>
<c:forEach items="${list}" var="book">
    ${book.bookId} + ${book.bookName} <br/>
</c:forEach>
</body>
</html>

测试

import com.hui.dao.BookDao;
import com.hui.domain.Book;
import com.hui.service.BookService;
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 org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestSpring {

    @Autowired
    BookService bookService;

    @Test
    public void run1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        BookService bookService = (BookService) ac.getBean("bookService");
        bookService.getAllBook();
    }

    @Test
    public void run2(){

        bookService.getAllBook();
    }

    @Test
    public void run3() throws IOException {

        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session = factory.openSession();
        BookDao dao = session.getMapper(BookDao.class);
        List<Book> books = dao.getAllBook();
        for (Book book : books) {
            System.out.println(book);

        }

        session.close();
        in.close();

    }

    @Test
    public void run4(){
        List<Book> books = bookService.getAllBook();
        for (Book book : books) {
            System.out.println(book);

        }
    }

}

以上是关于SSM整合的主要内容,如果未能解决你的问题,请参考以下文章

SSM框架整合

SSM 项目整合详细解读

SSM整合

520前,我放弃陪女朋友时间,被迫写代码:“SSM框架整合+excel文件上传到数据库+数据更新“

shiro整合SSM(spring_springmvc_mybatis)

ssm整合redis