当前位置:首页 > 科技新闻 > 其他 > 正文

SSM配置-Example
2022-08-29 23:51:33

SSM配置

目录结构

tree /f > catalogTree.txt

│ generatorConfig.xml
│ pom.xml
├─src
│ ├─main
│ ├─java
│ │ │ └─com
│ │ │ └─xxx
│ │ │ ├─controller
│ │ │ ├─dao
│ │ │ ├─entity
│ │ │ ├─listener
│ │ │ ├─mapper
│ │ │ ├─service
│ │ │ └─utils
│ │ ├─resources
│ │ │ │ applicationContext.xml
│ │ │ │ dbConfig.properties
│ │ │ │ logback.xml
│ │ │ │ mybatisConfig.xml
│ │ │ └─mapper
│ │ └─webapp
│ │ │ index.html
│ │ ├─static
│ │ └─WEB-INF
│ │ │ dispatcherServlet-servlet.xml
│ │ │ web.xml
│ │ └─views
..

配置

generatorConfig.xml

generatorConfig.xml (src 同级)

<?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">
        <!--        默认是false:添加注释,这个标签必须放在最前面   -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--        数据库连接信息-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/project_xxx"
                        userId="root"
                        password="0101">
        </jdbcConnection>
        <javaTypeResolver>
            <!--
                默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
                    true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal
            -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--        指定Entity生成位置-->
        <javaModelGenerator targetPackage="com.xxx.entity"
                            targetProject="srcmainjava">
            <property name="enableSubPackages" value="true"/>
        </javaModelGenerator>

        <!--        指定Mapper.xml文件生成位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="srcmain
esources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--        指定dao接口生成位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xxx.dao" targetProject="srcmainjava">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--        指定每个表的生成策略  -->
        <table tableName="表名" domainObjectName="生成类的类名"/>
    </context>

</generatorConfiguration>

dispatcherServlet-servlet.xml

dispatcherServlet-servlet.xml (WEB-INF下)

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

    <!--    spring mvc配置文件  包含网站跳转逻辑控制-->
    <!--扫描业务逻辑组件-->
    <context:component-scan base-package="com.xxx" use-default-filters="false">
        <!-- 只扫描控制器-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--    视图解析器,方便页面返回-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".html"/>
    </bean>

    <!--两个标准配置  -->
    <!-- 将spring mvc不能处理的请求交给tomcat -->
    <mvc:default-servlet-handler/>
    <!-- 能支持spring mvc更高级的一些功能,JSR303校验,快捷的ajax...映射动态请求 -->
    <mvc:annotation-driven/>

</beans>

dispatcherServlet-servlet.xml

web.xml (WEB-INF下)

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <!--  启动 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>

  <!--  字符编码过滤器 注意放在所有过滤器之前-->
  <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>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <!--    又有请求都处理编码格式-->
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--    使用Rest风格的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请求     HiddenHttpMethodFilter已被弃用-->
  <filter>
    <filter-name>formContentFilter</filter-name>
    <filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>formContentFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--  spring mvc 的前端控制器 拦截所有请求 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--指定mvc位置 如果不配置,需要有与web.xml文件同级的springDispatcherServlet-servlet.xml-->
    <!--            <init-param>-->
    <!--              <param-name>contextConfigLocation</param-name>-->
    <!--              <param-value></param-value>-->
    <!--            </init-param>-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--    拦截路径 所有-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

applicationContext.xml

applicationContext.xml (resources 下)

<?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:aop="http://www.springframework.org/schema/aop"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd ">
    <!--  配置文件,主要配置和业务逻辑有关的-->


    <!--  解决乱码  Content-Type: text/plain;charset=ISO-8859-1  -->
    <!--    <bean class="org.springframework.http.converter.StringHttpMessageConverter">-->
    <!--        <property name="supportedMediaTypes">-->
    <!--            <list>-->
    <!--                <value>text/plain;charset=UTF-8</value>-->
    <!--            </list>-->
    <!--        </property>-->
    <!--    </bean>-->


    <!--    扫描包  除了控制器以外的所有-->
    <context:component-scan base-package="com.xxx">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--    引入配置文件-->
    <context:property-placeholder location="classpath:dbConfig.properties"/>
    <!--    destroy-method="close"  注销区东程序 防止内存泄漏   -->
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="driverClass" value="${jdbc.class}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--================== 配置和MyBatis的整合=============== -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
        <property name="dataSource" ref="pooledDataSource"/>
        <!-- 指定mybatis,mapper文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--扫描所有dao接口的实现,加入到ioc容器中 -->
        <property name="basePackage" value="com.xxx.dao"/>
        <!--        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />-->
    </bean>

    <!-- 配置一个可以执行批量(select,update等。。。)的sqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <!-- 将defaultExecutorType配置为BATCH,可以批量更新操作缓存SQL以提高性能,
                但是有个缺陷就是无法获取update、delete返回的行数。-->
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>
    <!--=============================================  -->

    <!--     实现的接口放到ioc中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--   扫描接口-->
        <property name="basePackage" value="com.xxx.dao"/>
    </bean>

    <!--    事务控制    -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--   控制的数据源-->
        <property name="dataSource" ref="pooledDataSource"/>
    </bean>
    <!--  开启基于注解的事务     -->
    <aop:config>
        <!--  切入点表达式-->
        <aop:pointcut id="txPoint" expression="execution(* com.xxx.service..*(..))"/>
        <!--  配置事务增强-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>
    <!--   事务增强,切入方法    -->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <!--   所有方法都是事务方法-->
            <tx:method name="*"/>
            <!--   认为是获取的方法,只读-->
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

</beans>

dbConfig.properties

dbConfig.properties (resources 下)

jdbc.jdbcUrl = 
jdbc.class = 
jdbc.user = 
jdbc.password = 

logback.xml

logback.xml (resources 下)

<?xml version="1.0" encoding="UTF-8"?>
<!-- 从高到地低 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL -->
<!-- 日志输出规则  根据当前 ROOT 级别,日志输出时,级别高于root默认的级别时 会输出 -->
<!-- 以下 每个配置的 filter 是过滤掉输出文件里面,会出现高级别文件,依然出现低级别的日志信息,通过filter 过滤只记录本级别的日志-->

<!-- 属性描述
scan:设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true
scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。
当scan为true时,此属性生效。默认的时间间隔为1分钟。
debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">

    <!--定义日志文件的存储地址 -->
    <!--    <property name="LOG_HOME" value=""/>-->

    <!-- 控制台输出 -->
    <appender name="ConsoleLog" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!--Info文件输出-->
    <!-- 按照每天和固定大小(5MB)生成日志文件【最新的日志,是日期最大数字最大的】 -->
    <!--    <appender name="FileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
    <!--        &lt;!&ndash;如果只是想要 Info 级别的日志,只是过滤 info 还是会输出 Error 日志,因为 Error 的级别高,-->
    <!--      所以我们使用下面的策略,可以避免输出 Error 的日志,这种方式不能避免warn&ndash;&gt;-->
    <!--        &lt;!&ndash; 过滤日志 &ndash;&gt;-->
    <!--        <filter class="ch.qos.logback.classic.filter.LevelFilter">-->
    <!--            &lt;!&ndash;过滤 Error&ndash;&gt;-->
    <!--            <level>ERROR</level>-->
    <!--            &lt;!&ndash;匹配到就禁止&ndash;&gt;-->
    <!--            <onMatch>DENY</onMatch>-->
    <!--            &lt;!&ndash;没有匹配到就允许&ndash;&gt;-->
    <!--            <onMismatch>ACCEPT</onMismatch>-->
    <!--        </filter>-->


    <!--        &lt;!&ndash;只输出INFO&ndash;&gt;-->
    <!--        <filter class="ch.qos.logback.classic.filter.LevelFilter">-->
    <!--            &lt;!&ndash;过滤 INFO&ndash;&gt;-->
    <!--            <level>INFO</level>-->
    <!--            &lt;!&ndash;匹配到就禁止&ndash;&gt;-->
    <!--            <onMatch>ACCEPT</onMatch>-->
    <!--            &lt;!&ndash;没有匹配到就允许&ndash;&gt;-->
    <!--            <onMismatch>DENY</onMismatch>-->
    <!--        </filter>-->


    <!--        &lt;!&ndash;滚动策略&ndash;&gt;-->
    <!--        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">-->
    <!--            &lt;!&ndash;日志文件输出的文件名&ndash;&gt;-->
    <!--            <FileNamePattern>${LOG_HOME}/Info/DenseTubeManage_Info_%d{yyyy-MM-dd}.%i.log</FileNamePattern>-->
    <!--            &lt;!&ndash;日志文件保留天数&ndash;&gt;-->
    <!--            <MaxHistory>30</MaxHistory>-->
    <!--            &lt;!&ndash;日志文件最大的大小&ndash;&gt;-->
    <!--            <MaxFileSize>5MB</MaxFileSize>-->
    <!--        </rollingPolicy>-->
    <!--        &lt;!&ndash;格式化输出&ndash;&gt;-->
    <!--        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">-->
    <!--            &lt;!&ndash;格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符&ndash;&gt;-->
    <!--            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>-->
    <!--            <charset>UTF-8</charset>-->
    <!--        </encoder>-->
    <!--    </appender>-->

    <!--Error文件输出-->
    <!-- 按照每天和固定大小(5MB)生成日志文件【最新的日志,是日期最大数字最大的】 -->
    <!--    <appender name="FileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
    <!--        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">-->
    <!--            &lt;!&ndash;设置日志级别,过滤掉info日志,只输入error日志&ndash;&gt;-->
    <!--            <level>ERROR</level>-->
    <!--        </filter>-->
    <!--        &lt;!&ndash;滚动策略&ndash;&gt;-->
    <!--        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">-->
    <!--            &lt;!&ndash;日志文件输出的文件名&ndash;&gt;-->
    <!--            <FileNamePattern>${LOG_HOME}/Error/DenseTubeManage_Error_%d{yyyy-MM-dd}.%i.log</FileNamePattern>-->
    <!--            &lt;!&ndash;日志文件保留天数&ndash;&gt;-->
    <!--            <MaxHistory>30</MaxHistory>-->
    <!--            &lt;!&ndash;日志文件最大的大小&ndash;&gt;-->
    <!--            <MaxFileSize>5MB</MaxFileSize>-->
    <!--        </rollingPolicy>-->
    <!--        &lt;!&ndash;格式化输出&ndash;&gt;-->
    <!--        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">-->
    <!--            &lt;!&ndash;格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符&ndash;&gt;-->
    <!--            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>-->
    <!--            <charset>UTF-8</charset>-->
    <!--        </encoder>-->
    <!--    </appender>-->

    <!--日志等级设置-->
    <logger name="org.springframework" level="ALL"/>

    <root level="ALL">
        <appender-ref ref="ConsoleLog"/>
    </root>

    <logger name="com.xxx" level="ALL">
        <appender-ref ref="FileInfoLog"/>
        <appender-ref ref="FileErrorLog"/>
    </logger>

</configuration>

mybatisConfig.xml

mybatisConfig.xml (resources 下)

<?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>
    <settings>
        <!--        驼峰命名规则开启-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>

        <!--        <setting name="logImpl" value="LOG4J"/>-->
        <!-- 全局映射器启用缓存 -->
        <!--        <setting name="cacheEnabled" value="true" />-->
        <!--        &lt;!&ndash; 查询时,关闭关联对象即时加载以提高性能 &ndash;&gt;-->
        <!--        <setting name="lazyLoadingEnabled" value="true" />-->
        <!--        &lt;!&ndash; 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 &ndash;&gt;-->
        <!--        <setting name="aggressiveLazyLoading" value="false" />-->
        <!--        &lt;!&ndash; 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 &ndash;&gt;-->
        <!--        <setting name="multipleResultSetsEnabled" value="true" />-->
        <!--        &lt;!&ndash; 允许使用列标签代替列名 &ndash;&gt;-->
        <!--        <setting name="useColumnLabel" value="true" />-->
        <!--        &lt;!&ndash; 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 &ndash;&gt;-->
        <!--        <setting name="useGeneratedKeys" value="true" />-->
        <!--        &lt;!&ndash; 给予被嵌套的resultMap以字段-属性的映射支持 &ndash;&gt;-->
        <!--        <setting name="autoMappingBehavior" value="FULL" />-->
        <!--        &lt;!&ndash; 对于批量更新操作缓存SQL以提高性能  &ndash;&gt;-->
        <!--        <setting name="defaultExecutorType" value="SIMPLE" />-->
        <!-- 数据库超过25000秒仍未响应则超时 -->
        <!--        <setting name="defaultStatementTimeout" value="30" />-->
    </settings>

    <!--    别名-->
    <typeAliases>
        <package name="com.xxx.entity"/>
    </typeAliases>

    <!--    注册分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
    </plugins>
</configuration>

本文摘自 :https://www.cnblogs.com/