SSM框架整合的简单示例(XML版)

参考链接:SSM框架整合的简单示例(注解版)

1、数据库表

创建一个简单的数据库及t_book表,包含几个简单字段能够演示即可

CREATE DATABASE `ssm`;
CREATE TABLE `t_book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bname` varchar(32) DEFAULT NULL,
  `bcount` int(11) DEFAULT NULL,
  `descript` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8

2、创建工程

  • 新建一个普通的maven工程,不需要选模板,原始的maven工程

  • 导入相关依赖

    <!--数据库连接相关-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.49</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.5</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.3</version>
    </dependency>
    
    <!--数据相关,JSON-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.75</version>
    </dependency>
    
    <!--Mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>
    
    <!--SpringMVC相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.3</version>
    </dependency>
    
    <!--Web相关-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    
    <!--日志相关-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.3.0-alpha5</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>
    
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
    

3、三层框架的基本实现

3.1、实体类

Book.java

package com.yusian.entity;

public class Book {
    private Integer id;
    private String bname;
    private String bcount;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public String getBcount() {
        return bcount;
    }

    public void setBcount(String bcount) {
        this.bcount = bcount;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bname='" + bname + '\'' +
                ", bcount='" + bcount + '\'' +
                '}';
    }
}

3.2、Dao层

BookDao.java

package com.yusian.dao;

import com.yusian.entity.Book;

import java.util.List;

public interface BookDao {
    List<Book> findAll();
}

3.3、Service层

BookService.java

package com.yusian.service;

import com.yusian.entity.Book;

import java.util.List;

public interface BookService {
    List<Book> findAll();
}

BookServiceImpl.java

package com.yusian.service.impl;

import com.yusian.dao.BookDao;
import com.yusian.entity.Book;
import com.yusian.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {
    private BookDao bookDao;
    @Override
    public List<Book> findAll() {
        return bookDao.findAll();
    }

    public BookDao getBookDao() {
        return bookDao;
    }

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
}

4、Spring整合Mybatis的相关配置

Mysql相关配置:mysql.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://服务器地址/ssm?useSSL=false
username = root
password = ******

Mapper的相关配置:com/yusian/dao/BookDao.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.yusian.dao.BookDao">
    <select id="findAll" resultType="Book">
        select * from t_book;
    </select>
</mapper>

Spring的相关配置

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

    <!--引入配置文件-->
    <context:property-placeholder location="classpath:mysql.properties"/>

    <!--配置数据库-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

    <!--Mybatis工厂类-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.yusian.entity"/>
        <property name="mapperLocations">
            <list>
                <value>classpath:com/yusian/dao/*Dao.xml</value>
            </list>
        </property>
    </bean>

    <!--Mapper动态扫描-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
        <property name="basePackage" value="com.yusian.dao"/>
    </bean>

    <!--创建Service-->
    <bean id="bookService" class="com.yusian.service.impl.BookServiceImpl">
        <property name="bookDao" ref="bookDao"/>
    </bean>

    <!--SpringMVC创建控制器-->
    <bean id="/book" class="com.yusian.controller.BookController"/>
</beans>

5、单元测试

到此为止,对数据的相关操作应该是没有问题了,可能测试各层的可用性:

package com.yusian;

import com.yusian.entity.Book;
import com.yusian.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class SSMTest {
    @Test
    public void serviceTest() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService) ctx.getBean("bookService");
        List<Book> books = bookService.findAll();
        for (Book book : books) {
            System.out.println("book = " + book);
        }
    }
}

运行结果:

book = Book{id=1, bname='西游记', bcount='10'}
book = Book{id=2, bname='三国演义', bcount='20'}
book = Book{id=3, bname='水浒传', bcount='30'}
book = Book{id=4, bname='红楼梦', bcount='40'}

Process finished with exit code 0

6、SpringMVC整合Web应用

6.1、基础配置

  • 将当前Module转换为Web项目:Add Framework Support,勾选Web Application
  • web.xml中配置servlet,由DispatcherServlet统一接管请求
  • Spring配置指向applicationContext.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>springmvc</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>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

6.2、编写控制器

BookController.java

package com.yusian.controller;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.yusian.entity.Book;
import com.yusian.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class BookController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService) ctx.getBean("bookService");
        List<Book> books = bookService.findAll();
        return new ModelAndView(new FastJsonJsonView()).addObject(books);
    }
}

6.3、测试

浏览器中访问http://localhost:8080/book即可看到查询出来的图书列表Json字符串

One thought on “SSM框架整合的简单示例(XML版)

  1. Pingback: SSM框架整合的简单示例(注解版) | 年年有"余"

Leave a Reply