三大框架整合ssm:SpringMVC + Spring + Mybatis

github地址: https://github.com/laichilueng/ssm

首先打开IDE ,我这边用的是myeclipse10, 创建一个web项目,添加maven支持。

三大框架整合ssm:SpringMVC + Spring + Mybatis_第1张图片

接着我们修改pom.xml文件,使用maven管理我们的jar包,这里可以参考我的pom.xml文件

pom.xml

<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.0modelVersion>
    <groupId>SSMgroupId>
    <artifactId>SSMartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>
    <name>SSMname>
    <description />
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
        dependency>

        
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.1.1version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.37version>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.3.0version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.2.3version>
        dependency>

        
        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.5.4version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
        dependency>

        
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>4.1.7.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
            <version>2.7.3version>
        dependency>
        <dependency>
            <groupId>com.dyuproject.protostuffgroupId>
            <artifactId>protostuff-coreartifactId>
            <version>1.0.8version>
        dependency>
        <dependency>
            <groupId>com.dyuproject.protostuffgroupId>
            <artifactId>protostuff-runtimeartifactId>
            <version>1.0.8version>
        dependency>

        
        <dependency>
            <groupId>commons-collectionsgroupId>
            <artifactId>commons-collectionsartifactId>
            <version>3.2version>
        dependency>
        <dependency>
            <groupId>org.apache.openejbgroupId>
            <artifactId>javaee-apiartifactId>
            <version>5.0-1version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.1version>
            <scope>providedscope>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-war-pluginartifactId>
            plugin>
            <plugin>
                <artifactId>maven-compiler-pluginartifactId>
                <configuration>
                    <source>1.5source>
                    <target>1.5target>
                configuration>
            plugin>
        plugins>
        <finalName>ssmfinalName>
    build>
project>

然后我们创建对应的目录文件夹以及对应的包,并将resources和java添加到source里面。

创建后的目录
三大框架整合ssm:SpringMVC + Spring + Mybatis_第2张图片

到了这里,目录的框架已经出来了,现在我们开始写配置文件。

首先我们配置mybatis,先在spring的文件夹里面创建一个spring-dao.xml

  1. 读入数据库连接相关参数(可选)
  2. 配置数据连接池
  3. 配置连接属性,可以不读配置项文件直接在这里写死
  4. 配置c3p0,只配了几个常用的
  5. 配置SqlSessionFactory对象(mybatis)

spring-dao.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"
    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">
    
    
    <context:property-placeholder location="classpath:jdbc.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" />
        <property name="automaticTestTable" value="test_c3p0"/>
        <property name="idleConnectionTestPeriod" value="100000" />
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource" />
        
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        
        <property name="typeAliasesPackage" value="com.dnf.entity" />
        
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    bean>

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

然后在resources文件夹里面创建一个文件jdbc.properties,用来填写数据库信息

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

因为使用了mybatis,所以我们在resource文件夹里创建一个mybatis-donfig.xml,用于配置mybatis

mybatis-config.xml



<configuration>
    
    <settings>
        
        <setting name="useGeneratedKeys" value="true" />

        
        <setting name="useColumnLabel" value="true" />

        
        <setting name="mapUnderscoreToCamelCase" value="true" />
    settings>
configuration>

至此,mybatis的配置基本完成,下面配置service层
首先在spring里面创建spring-service.xml文件,用于:

  1. 扫描service包所有注解 @Service
  2. 配置事务管理器,把事务管理交由spring来完成
  3. 配置基于注解的声明式事务,可以直接在方法上@Transaction

spring-service.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:tx="http://www.springframework.org/schema/tx"
    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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <context:component-scan base-package="com.lzl.service" />

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

    
    <tx:annotation-driven transaction-manager="transactionManager" />
beans>

接着我们配置controller,在spring文件夹里面创建spring-mvc.xml文件

  1. 开启SpringMVC注解模式,可以使用@RequestMapping,@PathVariable,@ResponseBody等
  2. 对静态资源处理,如js,css,jpg等
  3. 配置jsp 显示ViewResolver,例如在controller中某个方法返回一个string类型的”login”,实际上会返回”/WEB-INF/login.jsp”
  4. 扫描web层 @Controller

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
    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
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    
    
    
    <mvc:annotation-driven />

    
    <mvc:default-servlet-handler />
    <mvc:resources mapping="/resources/**" location="/resources/"/> 

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


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



    
    <mvc:interceptors>
        <mvc:interceptor>
            
            <mvc:mapping path="/**" />
            
            <mvc:exclude-mapping path="/resources/**"/>
            <bean class="com.lzl.interceptors.LoginInterceptor">bean>
        mvc:interceptor>
    mvc:interceptors>

     
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Exception">error/500prop>
                <prop key="java.lang.Throwable">error/500prop>
            props>
        property>
        <property name="statusCodes">
            <props>
                <prop key="errors/500">500prop>
            props>
        property>
        
        <property name="warnLogCategory" value="WARN">property>
        
        <property name="defaultErrorView" value="error/500">property>
        
        <property name="defaultStatusCode" value="500">property>
    bean>
beans>

最后就是修改web.xml文件,他位于webapp/WEB-INF下

web.xml


<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_3_1.xsd"
    version="3.1" metadata-complete="true">
    <display-name>display-name>
    <welcome-file-list>
        <welcome-file>index.jspwelcome-file>
    welcome-file-list>

    
    <servlet>
        <servlet-name>seckill-dispatcherservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring/spring-*.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>seckill-dispatcherservlet-name>
        
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

在开发中,我们经常使用到日志输出,所以这里配置一个日志配置文件logback.xml,同样在resource里面创建文件。

logback.xml


<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
        encoder>
    appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
    root>
configuration>

三大框架整合ssm:SpringMVC + Spring + Mybatis_第3张图片

那么到目前为止我们一共配置了7个xml文件,现在我们测试一下使用tomcat跑,看看是否出错。(tomcat的配置在这里就不说了,大伙上网学习下)

三大框架整合ssm:SpringMVC + Spring + Mybatis_第4张图片

框架是能跑起来的,那么目前为止我们已经成功整合了三大框架。下面我们结合数据库来测试该框架。首先在数据库中建立一个test库,并创建一张表。

创建一个测试表给c3p0连接池做测试
CREATE TABLE `test_c3p0` (
  `id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `book` (
  `id` varchar(200) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `author` varchar(50) DEFAULT NULL,
  `number` int(10) NOT NULL,
  PRIMARY KEY (`id`)
);

然后往里面添加一些数据, 然后修改jdbc.properties文件,填写数据库信息,如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

在项目的entity里面创建实体类Book.java

Book.java

package com.lzl.entity;

public class Book {
    private String id;
    private String name;
    private String author;
    private int number;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", author=" + author
                + ", number=" + number + "]";
    }
}

在dao中创建接口BookDao.java

BookDao.java

package com.lzl.dao;

import java.util.List;

import com.lzl.entity.Book;

public interface BookDao {
    List query4books();

}

接下来我们不需要实现这个接口,而是需要写mapper文件,这样mybatis会帮我们自动实现接口,在mapper中创建BookDao.xml

BookDao.xml




<mapper namespace="com.lzl.dao.BookDao">
    
    <select id="query4books" resultType="Book">
        SELECT
            id,
            name,
            author,
            number
        FROM
            book
    select>
mapper>

dao层写完了,那么我们写对应的test方法。因为后面的业务逻辑需要写很多测试方法,所以我们抽象出一个BaseTest类,当我们调用单元测试前,先加载三大框架的配置文件,那么在写其他测试类时,只需要继承这个BaseTest类就可以了。

在test/java里面创建BaseTest.java
BaseTest.java

package com.lzl;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 配置spring和junit整合,junit启动时加载springIOC容器 spring-test,junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
// 告诉junit spring配置文件
@ContextConfiguration({ "classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml" })
public class BaseTest {

}

创建TestBookDao.java

package com.lzl.dao;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.lzl.BaseTest;
import com.lzl.entity.Book;

public class TestBookDao extends BaseTest{

    @Autowired
    private BookDao dao;

    @Test
    public void testquery4books(){
        List list = new ArrayList();
        list = dao.query4books();
        for(Book book : list){
            System.out.println(book.toString());
        }
    }
}

进行junit测试,可看到测试结果
三大框架整合ssm:SpringMVC + Spring + Mybatis_第5张图片

至此,我们的dao层测试已经完成了,下面将进行service层和controller层的测试。

首先在service中创建接口BookService.java

package com.lzl.service.impl;

import java.util.List;

import com.lzl.entity.Book;

public interface BookService {
    List query4books();
}

然后在service.impl中创建实现类BookServiceImpl.java

package com.lzl.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lzl.dao.BookDao;
import com.lzl.entity.Book;

//这里一定要加上service这个注解,这样spring初始化的时候会扫描该实现类
@Service
public class BookServiceImpl implements BookService{

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private BookDao bookDao;

    @Override
    public List query4books() {
        // TODO Auto-generated method stub
        return bookDao.query4books();
    }
}

接着我们创建BookController类
BookController.java

package com.lzl.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lzl.entity.Book;
import com.lzl.service.impl.BookService;

@Controller
@RequestMapping("/")
public class BookController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BookService service;

// 该方法将请求映射到Book.jsp这个页面上
    @RequestMapping("/book")
    public String toBookPage(HttpServletRequest request){
        List list = service.query4books();
//      这里在请求Book页面时,查询所有的book并将其存到request里面
        if(list != null){
            for(Book book : list){
                logger.info(book.toString());
            }
            request.setAttribute("books", list);
        }
//      返回string类型,jsp渲染器会自动寻找/jsp/Book.jsp
        return "Book";
    }
}

接着在webapp/WEB-INF/jsp中创建Book.jsp,并将数据展示

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<base href="<%=basePath%>">
<title>Booktitle>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="styles.css">
head>
<body>
    <div align="center">
        <table>
            <tr>
                <td>idtd>
                <td>nametd>
                <td>authortd>
                <td>numbertd>
            tr>
            <c:forEach var="book" items="${ books}">
                <tr>
                    <td>${ book.id}td>
                    <td>${ book.name}td>
                    <td>${ book.author}td>
                    <td>${ book.number}td>
                tr>
            c:forEach>
        table>
    div>
body>
html>

然后请求页面
三大框架整合ssm:SpringMVC + Spring + Mybatis_第6张图片


可以看到成功的把数据库中的数据取到页面中,至此三大框架测试完成。源码和jar包我已经打包放在了github上,需要的可以去下载,喜欢的请给个star。
github地址: https://github.com/laichilueng/ssm
若有什么疑问,欢迎与我联系,谢谢。

你可能感兴趣的:(Java)