当前位置 : 主页 > 网页制作 > html >

SSM三大框架整合梳理

来源:互联网 收集:自由互联 发布时间:2021-06-12
整合步骤 0、搭建动态web项目 1、需要的jar包 spring(包括springmvc) mybatis相关jar包 mybatis与spring的整合包(个人建议尽量使用高版本的,避免出现一些奇怪的错误mybatis-spring-2.0.2.jar) 数据

整合步骤

0、搭建动态web项目

1、需要的jar包

  1. spring(包括springmvc)
  2. mybatis相关jar包
  3. mybatis与spring的整合包(个人建议尽量使用高版本的,避免出现一些奇怪的错误mybatis-spring-2.0.2.jar)
  4. 数据库驱动包(mysql-connector-java-5.1.44.jar)
  5. 第三方连接池(druid-1.1.10.jar,也可用spring的dbcp连接池或c3p0连接池c3p0-0.9.5.2.jar)
  6. json依赖包Jackson
  7. jstl标签库

    以下为可选
  8. 另外,若要使用mybatis逆向工程,需导入mybatis-generator-core-1.3.5.jar以及增加配置文件mbg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 配置数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/ssm_crud" userId="root"
            password="123">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 指定Javabean生成的位置 -->
        <javaModelGenerator targetPackage="com.fei.pojo"
            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper"
            targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 指定mapper(dao)接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.fei.mapper" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 指定每个表的生成策略 -->
        <table tableName="tbl_emp" domainObjectName="Employee"></table>
        <table tableName="tbl_dept" domainObjectName="Department"></table>

    </context>
</generatorConfiguration>

还有核心主程序

package com.fei.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

/**
 * mybatis代码生成主程序
 * @Author xiaofei
 * @CreateDate 2019年9月2日
 */
public class MBGTest {
    
    public static void main(String[] args) throws Exception {
        
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mybatis-generator.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        
        System.out.println("代码生成完毕!请查收");
    }
}
  1. 若要使用分页插件,还需导入pagehelper-5.1.2.jar和jsqlparser-1.0.jar
  2. 若要使用文件上传还要另外导相关的包

2、整合思路

  1. dao层
    • sqlMapConfig.xml,空文件即可,但是需要文件头
    • applicationContext-dao.xml
      • 数据库连接池druid
      • sqlSessionFactory对象,需要spring和mybatis整合包下的
      • 配置mapper文件扫描器,Mapper动态代理开发增强版
  2. service层
    • applicationContext-service.xml:配置包扫描器,扫描@service注解的组件类
    • applicationContext-tx.xml配置事务
  3. web层
    • springmvc.xml:核心三大组件
  4. web.xml:前端控制器、拦截器、编码过滤器等
    也可以将dao层和service层的配置在一个文件中

下面是配置文件,我把dao层的applicationContext-dao.xml和applicationContext-service.xml写到一个配置文件spring-mybatis.xml中

3、配置文件编写

  1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd 
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 
                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd ">
    
    <!-- spring的配置文件,这里主要配置业务和逻辑有关的配置,包括数据源,事务控制 -->
    <context:component-scan base-package="com.fei.service">
        <!-- <context:exclude-filter type="annotation" expression=" org.springframework.stereotype.Controller"/> -->
    </context:component-scan>
    
    <!-- ==================数据源的配置start================== -->
    <!-- 告诉spring让他去读取db.properties配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <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>
    <!-- ==================数据源的配置end================== -->


    <!-- ==============配置spring和mybatis的整合start============== -->
    <!-- MyBatis工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 指定mybatis核心配置文件的位置 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
        <!-- 指定mapper文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置扫描器,将mybatis接口的实现(一个代理对象)加入到ioc容器中,Mapper动态代理开发,扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定基本包,扫描所有mapper接口的实现,加入到ioc容器中 -->
        <property name="basePackage" value="com.fei.mapper"/>
    </bean>
    
    <!-- 配置一个可以执行批量操作的sqlSession -->
    <bean id="sqlSession" class=" org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>
    <!-- ==============配置spring和mybatis的整合end============== -->


    <!-- ====================事务控制的配置start==================== -->
    <!-- 注解事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 控制住数据源里面连接的开启、关闭、回滚等操作 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 1)开启基于注解的事务 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager"/> -->
    <!-- 2)开启基于xml配置的事务(比较重要的都是用配置形式) -->
    <aop:config>
        <!-- 切入点表达式 -->
        <aop:pointcut expression="execution(* com.fei.service..*(..))" id="txPoint"/>
        <!-- 配置事务增强 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>
    <!-- 配置事务增强,事务如何切入 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 所有的方法都是事务方法 -->
            <tx:method name="*"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- ====================事务控制的配置end==================== -->
    
    
    <!-- spring配置文件核心点(数据源,与mybatis的整合,事务控制) -->
        
    <!-- springmvc的异常处理器 -->
    <!-- <bean class="com.fei.exception.CustomExceptionResolver"/> -->

</beans>

  1. springmvc.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"
    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.xsd">
                        
    <!-- springmvc的配置文件,主要包含网站跳转的逻辑控制 -->
    
    <!-- 配置controller扫描,精准扫描 -->
    <context:component-scan base-package="com.fei.controller" />

    <!-- 定义视图文件解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- 两个标准配置 -->
    <!-- 将springmvc不能处理的请求交给tomcat -->
    <mvc:default-servlet-handler/>
    <!-- 能支持一些springmvc更高级的一些功能,JSR303校验,快捷的ajax...,映射动态请求 -->
    <mvc:annotation-driven/>
    
    <!-- ================ 上面是springmvc的基本配置 ================ -->
    <!-- 对静态资源放行 -->
    <!-- <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/fonts/" mapping="/fonts/**"/>
    <mvc:resources location="/img/" mapping="/img/**"/>
    <mvc:resources location="/bower_components/" mapping="/bower_components/**"/>
    <mvc:resources location="/dist/" mapping="/dist/**"/>
    <mvc:resources location="/plugins/" mapping="/plugins/**"/>  -->
    
    <!-- 配置拦截器(多个) -->
    <!-- <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/login"/>
            <mvc:exclude-mapping path="/static/**"/>
            <bean class="com.fei.ssmcrm.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors> -->
    
    <!-- 读取配置文件,解决硬编码问题 -->
    <!-- <context:property-placeholder location="classpath:code-params.properties" /> -->
    
</beans>

  1. db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm_crud?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123
  1. sqlMapConfig.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="com.fei.pojo"/>
    </typeAliases>
    
    <!-- pagehelper分页插件注册 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 分页参数合理化 -->
            <property name="resonable" value="true"/>
        </plugin>
    </plugins>
    
</configuration>

  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_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <!-- 1、启动spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 2、springmvc的前端控制器,拦截所有请求 -->
    <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:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 3、字符编码过滤器,一定要放在所有过滤器之前 -->
    <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>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 4、使用Restful风格的URI,将页面普通的post请求转为指定的delete或put请求 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 处理直接发送put请求的过滤器 -->
    <filter>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <filter-class> org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

下面是项目的包结构以及lib目录

项目包结构

分享图片

lib目录

分享图片

网友评论