美文网首页
SSM(Spring+SpringMVC+MyBatis)框架整

SSM(Spring+SpringMVC+MyBatis)框架整

作者: Samon_ | 来源:发表于2018-08-07 11:44 被阅读0次

一、 Spring+MyBatis整合

1. 在pom.xml中添加Spring依赖和MyBatis依赖

  • Spring核心包:core、beans、context、tx、web、test
  • SpringMVC:spring-webmvc
  • mysql数据库连接驱动:mysql-connector-java
  • MyBatis:mybatis、mybatis-spring
  • 数据库连接池驱动,如:Druid,用于配置数据库
  • com.alibaba.json用于格式化日志输出
  • jackson:?

示例代码:

<?xml version="1.0" encoding="UTF-8"?>

<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.0</modelVersion>

  <groupId>com.cmos</groupId>
  <artifactId>ssmdemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssmdemo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
      <maven.compiler.source>1.7</maven.compiler.source>
      <maven.compiler.target>1.7</maven.compiler.target>

      <!-- 设置项目编码编码 -->
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <!-- spring版本号 -->
      <spring.version>4.0.3.RELEASE</spring.version>
      <!-- mybatis版本号 -->
      <mybatis.version>3.4.1</mybatis.version>
  </properties>

  <dependencies>

      <!-- java ee -->
      <dependency>
          <groupId>javax</groupId>
          <artifactId>javaee-api</artifactId>
          <version>7.0</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/junit/junit -->
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
      </dependency>


      <!-- https://mvnrepository.com/artifact/log4j/log4j -->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
      </dependency>
      <!-- 实现slf4j接口并整合 -->
      <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.2.2</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.49</version>
      </dependency>

      <!-- JSON -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.8.7</version>
      </dependency>


      <!-- 数据库 -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.12</version>
          <scope>runtime</scope>
      </dependency>

      <!-- 数据库连接池 -->
      <dependency>
          <groupId>com.mchange</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.5.2</version>
      </dependency>

      <!-- MyBatis -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
      </dependency>

      <!-- mybatis/spring整合包 -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.1</version>
      </dependency>

      <!-- Spring -->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <!--MyBatis generator dependency -->
      <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.4</version>
      </dependency>

  </dependencies>

  <build>
      <finalName>ssmdemo</finalName>
      <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
          <plugins>
              <plugin>
                  <artifactId>maven-clean-plugin</artifactId>
                  <version>3.0.0</version>
              </plugin>
              <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
              <plugin>
                  <artifactId>maven-resources-plugin</artifactId>
                  <version>3.0.2</version>
              </plugin>
              <plugin>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.7.0</version>
              </plugin>
              <plugin>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>2.20.1</version>
              </plugin>
              <plugin>
                  <artifactId>maven-war-plugin</artifactId>
                  <version>3.2.0</version>
              </plugin>
              <plugin>
                  <artifactId>maven-install-plugin</artifactId>
                  <version>2.5.2</version>
              </plugin>
              <plugin>
                  <artifactId>maven-deploy-plugin</artifactId>
                  <version>2.8.2</version>
              </plugin>

              <!--MyBatis generator plugin-->
              <plugin>
                  <groupId>org.mybatis.generator</groupId>
                  <artifactId>mybatis-generator-maven-plugin</artifactId>
                  <version>1.3.4</version>
                  <configuration>
                      <verbose>true</verbose>
                      <overwrite>true</overwrite>
                  </configuration>
              </plugin>
          </plugins>
      </pluginManagement>
  </build>
</project>

2. 在resources中创建jdbc.properties文件,配置数据库连接参数

  • 将数据库连接配置参数保存在该文件中
jdbc.driver=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
#用户名
jdbc.username=root
#密码
jdbc.password=admin
#最大连接数
maxPoolSize=30
#最小连接数
minPoolSize=10
#关闭连接后不自动commit
autoCommitOnClose=false
#获取连接超时时间
checkoutTimeout=10000
#当获取连接失败重试次数
acquireRetryAttempts=2
  • 如果工程中使用了log4j,需要在resources中创建log4j.properties文件,否则在项目启动过程中会出现log4j没有正确初始化的warning
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

3. 在resources中创建spring-mybatis.xml文件

  <!-- 配置数据库相关参数properties的属性:${url} -->
  <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="${maxPoolSize}"/>
      <property name="minPoolSize" value="${minPoolSize}"/>
      <property name="autoCommitOnClose" value="${autoCommitOnClose}"/>
      <property name="checkoutTimeout" value="${checkoutTimeout}"/>
      <property name="acquireRetryAttempts" value="${acquireRetryAttempts}"/>
  </bean>

  <!-- 配置SqlSessionFactory对象 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <!-- 注入数据库连接池 -->
      <property name="dataSource" ref="dataSource"/>
      <!-- 扫描model包 使用别名 -->
      <property name="typeAliasesPackage" value="com.cmos.ssm.beans"/>
      <!-- 扫描sql配置文件:mapper需要的xml文件 -->
      <property name="mapperLocations" value="classpath:mapper/*.xml"/>
  </bean>

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

  <!-- 配置事务管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <!-- 注入数据库连接池 -->
      <property name="dataSource" ref="dataSource"/>
  </bean>

  <!-- 配置基于注解的声明式事务 -->
  <tx:annotation-driven transaction-manager="transactionManager"/>

4. 使用MyBatis genenrator生成代码

二、 Spring+SpringMVC整合

  1. 在resources中创建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:p="http://www.springframework.org/schema/p"
     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-3.1.xsd
                      http://www.springframework.org/schema/context
                      http://www.springframework.org/schema/context/spring-context-3.1.xsd
                      http://www.springframework.org/schema/mvc
                      http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

  <!-- 启用自动扫描 -->
  <context:component-scan base-package="com.cmos.ssm" />

  <!-- 启用注解驱动的SpringMVC -->
  <mvc:annotation-driven/>

  <!-- 配置JSP视图解析器 -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <!-- 给controller返回的视图名加上特定的前缀和后缀,从而将视图名解析为某个路径下的一个JSP页面 -->
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
  </bean>

  <!-- 配置拦截器 -->
  <!--<mvc:interceptors>
      <mvc:interceptor>
          &lt;!&ndash; <mvc:mapping path="/**"/>拦截所有 &ndash;&gt;
          <mvc:mapping path="/user/**"/>
          <mvc:mapping path="/role/**"/>
          <mvc:mapping path="/function/**"/>
          <mvc:mapping path="/news/**"/>
          <mvc:mapping path="/img/**"/>
          <bean class="com.crossoverJie.intercept.Intercept"></bean>
      </mvc:interceptor>
  </mvc:interceptors>-->
</beans>
  1. 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>Archetype Created Web Application</display-name>

    <!-- Spring和mybatis的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.xml</param-value>
    </context-param>

    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <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>

    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- Spring MVC servlet -->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

三、 编写iservice、service.impl、controller

  1. 测试页面showUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>测试</title>
  </head>

  <body>
    ${user.user_name}
  </body>
</html>
    • IUserSV:
package com.cmos.ssm.iservice;

import com.cmos.ssm.beans.User;

public interface IUserSV {
    User getUserByID(int id);
}
  • UserSVImple:
package com.cmos.ssm.service.impl;

import com.cmos.ssm.beans.User;
import com.cmos.ssm.dao.UserDAO;
import com.cmos.ssm.iservice.IUserSV;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserSVImpl implements IUserSV {

    @Autowired
    private UserDAO userDAO;

    @Override
    public User getUserByID(int id) {
        return userDAO.selectByPrimaryKey(id);
    }
}
  • UserController
package com.cmos.ssm.controller;

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 com.cmos.ssm.iservice.IUserSV;
import com.cmos.ssm.beans.User;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class UserController {

    @Autowired
    private IUserSV userService;

    @RequestMapping(value = "/showUser", method = RequestMethod.GET)
    public String toIndex(Model model){
        User user = this.userService.getUserByID(1);
        model.addAttribute("user", user);
        return "showUser";
    }
}
  1. 打包
mvn clean package
  1. 将打包后的.war文件放在tomcat目录下的webapps文件夹中,启动tomcat服务器

四、 测试通过,搭建完成

测试结果页面
搭建完成后的工程目录

相关文章

网友评论

      本文标题:SSM(Spring+SpringMVC+MyBatis)框架整

      本文链接:https://www.haomeiwen.com/subject/ycmgvftx.html