码迷,mamicode.com
首页 > 其他好文 > 详细

SSH整合

时间:2019-08-18 00:01:04      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:created   let   ||   break   list()   未使用   encoding   pom   c3p0连接池   

简介

SSH在J2EE项目中表示了3种框架,即 Spring + Struts +Hibernate。 Struts对Model,View和Controller都提供了对应的组件。Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。 Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,可以应用在任何使用JDBC的场合,可以在Servlet/JSP的Web应用中使用,也可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。

演示:

1、导入所需要的pom依赖 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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.hxc</groupId>
    <artifactId>ssh</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ssh Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <hibernate.version>5.2.12.Final</hibernate.version>
        <mysql.version>5.1.44</mysql.version>
        <spring.version>5.0.1.RELEASE</spring.version>
        <struts2.version>2.5.13</struts2.version>
        <slf4j.version>1.7.7</slf4j.version>
        <log4j.version>2.9.1</log4j.version>
        <disruptor.version>3.2.0</disruptor.version>
        <junit.version>4.12</junit.version>
        <servlet.version>4.0.0</servlet.version>
        <jstl.version>1.2</jstl.version>
        <standard.version>1.1.2</standard.version>
        <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
    </properties>
    <dependencies>
        <!-- 1、hibernate相关(5.2.12.Final) -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- 2、spring相关(5.0.1.RELEASE) -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</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-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 3、struts2相关(2.5.13) -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <!-- 4、log配置 -->
        <!-- log配置:Log4j2 + Slf4j -->
        <!-- slf4j核心包 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!--用于与slf4j保持桥接 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <!--核心log4j2jar包 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <!--web工程需要包含log4j-web,非web工程不需要 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>${log4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <!--需要使用log4j2的AsyncLogger需要包含disruptor -->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>${disruptor.version}</version>
        </dependency>

        <!-- 5、other -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${standard.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>${tomcat-jsp-api.version}</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>ssh</finalName>
        <plugins>
            <!--第一步就是配置maven-compiler-plugin插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

 导入ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
    <!--path:指定在硬盘上存储对象的路径-->
    <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
    <diskStore path="java.io.tmpdir"/>


    <!--defaultCache:默认的管理策略-->
    <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
    <!--maxElementsInMemory:在内存中缓存的element的最大数目-->
    <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
    <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
    <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
    <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
    <!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
    <!--FIFO:first in first out (先进先出)-->
    <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
    <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
    <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>


    <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
    <cache name="stuCache" eternal="false" maxElementsInMemory="100"
           overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

 

 

 导入log4j2.xml

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

<!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR 
    < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <!-- 配置日志文件输出目录 ${sys:user.home} -->
        <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
        <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
        <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
    </Properties>

    <Appenders>
        <!--这个输出控制台的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="trace" onMatch="ACCEPT"
                onMismatch="DENY" />
            <!-- 输出日志的格式 -->
            <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 
                %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M 
                : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
            <PatternLayout pattern="${PATTERN}" />
        </Console>

        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
        <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
        <File name="log" fileName="logs/test.log" append="false">
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
            filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="info" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
                <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
                <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
                <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
            </Policies>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
            filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="2 kB" />
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
            filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
            </Policies>
        </RollingFile>

    </Appenders>

    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
    <Loggers>
        <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>

        <!-- 第三方日志系统 -->
        <logger name="org.springframework" level="ERROR" />
        <logger name="org.hibernate" level="ERROR" />
        <logger name="org.apache.struts2" level="ERROR" />
        <logger name="com.opensymphony.xwork2" level="ERROR" />
        <logger name="org.jboss" level="ERROR" />


        <!-- 配置日志的根节点 -->
        <root level="all">
            <appender-ref ref="Console" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn" />
            <appender-ref ref="RollingFileError" />
        </root>

    </Loggers>

</Configuration>

 

注入数据库配置文件db.properties

db.username=root
db.password=123
db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mytable?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
db.initialPoolSize=10
db.maxPoolSize=20
db.minPoolSize=5
db.maxIdleTime=60
db.acquireIncrement=5
db.maxStatements=0
db.idleConnectionTestPeriod=60
db.acquireRetryAttempts=30
db.breakAfterAcquireFailure=true
db.testConnectionOnCheckout=false

spring-hibernate.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:aop="http://www.springframework.org/schema/aop"
    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/aop http://www.springframework.org/schema/aop/spring-aop-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/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 1、注册jdbc相关的配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 2、配置数据库连接池C3P0 -->
    <!-- 注册数据库连接文件db.properties -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置c3p0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="driverClass" value="${db.driverClass}"></property>
        <property name="jdbcUrl" value="${db.jdbcUrl}"></property>

        <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
        <property name="initialPoolSize" value="${db.initialPoolSize}"></property>
        <!--连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize" value="${db.maxPoolSize}"></property>
        <!--连接池中保留的最小连接数。 -->
        <property name="minPoolSize" value="${db.minPoolSize}" />
        <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime" value="${db.maxIdleTime}" />

        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement" value="${db.acquireIncrement}" />

        <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 
            所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
            0 -->
        <property name="maxStatements" value="${db.maxStatements}" />

        <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
        <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" />

        <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
        <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" />

        <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 
            如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
        <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" />

        <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 
            或automaticTestTable 等方法来提升连接测试的性能。Default: false -->
        <property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" />
    </bean>

    <!-- 3、配置sessionfactory相关信息 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <!-- hibernate相关属性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
                <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt -->
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <!-- 实体映射文件 -->
        <property name="mappingResources">
            <list>
                <value>com/hxc/book/entity/book.hbm.xml</value>
            </list>
        </property>
    </bean>

    <!-- 4、配置事务 -->
    <!--声明式事务配置开始 -->
    <!-- 
        静态代理:
            一个代理对象->一个目标对象
            BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz
            OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)->    OrderBiz
        
        动态代理:
            一个代理对象->多个目标对象
     -->
    
    <!--1) 开启自动代理 -->
    <aop:aspectj-autoproxy />

    <!--2) 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!--3) 定义事务特性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />

            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />

            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />

            <tx:method name="load*" propagation="REQUIRED" read-only="true" />
            <tx:method name="list*" propagation="REQUIRED" read-only="true" />
            <tx:method name="select*" propagation="REQUIRED" read-only="true" />
            <tx:method name="query*" propagation="REQUIRED" read-only="true" />

            <tx:method name="do*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!--4) 定义切入点 -->
    <aop:config>
        <!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] -->
        <!-- A: 返回类型,*表示返回类型不限 -->
        <!-- B: 包名,*..表示包名不限 -->
        <!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 -->
        <!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 -->
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Biz.*(..))" />
    </aop:config>
    <!-- 声明式事务配置结束 -->

    <!-- 5、配置HibernateTemplate -->
    <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 6、分模块开发(只配置base模块) -->
    <bean class="com.hxc.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean>
    <bean class="com.hxc.base.dao.BaseDao" abstract="true" id="baseDao" >
        <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    </bean>
    <bean class="com.hxc.base.biz.BaseBiz" abstract="true" id="baseBiz"></bean>
    <bean class="com.hxc.base.web.BaseAction" abstract="true" id="baseAction"></bean>
</beans>

log4j2.xml

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

<!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR 
    < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <!-- 配置日志文件输出目录 ${sys:user.home} -->
        <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
        <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
        <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
    </Properties>

    <Appenders>
        <!--这个输出控制台的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="trace" onMatch="ACCEPT"
                onMismatch="DENY" />
            <!-- 输出日志的格式 -->
            <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 
                %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M 
                : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
            <PatternLayout pattern="${PATTERN}" />
        </Console>

        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
        <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
        <File name="log" fileName="logs/test.log" append="false">
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
            filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="info" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
                <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
                <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
                <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
            </Policies>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
            filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="2 kB" />
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
            filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
            </Policies>
        </RollingFile>

    </Appenders>

    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
    <Loggers>
        <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>

        <!-- 第三方日志系统 -->
        <logger name="org.springframework" level="ERROR" />
        <logger name="org.hibernate" level="ERROR" />
        <logger name="org.apache.struts2" level="ERROR" />
        <logger name="com.opensymphony.xwork2" level="ERROR" />
        <logger name="org.jboss" level="ERROR" />


        <!-- 配置日志的根节点 -->
        <root level="all">
            <appender-ref ref="Console" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn" />
            <appender-ref ref="RollingFileError" />
        </root>

    </Loggers>

</Configuration>

 

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <include file="struts-default.xml"></include>
    <include file="struts-base.xml"></include>
    <include file="struts-book.xml"></include>
</struts>

 

struts-base.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.configuration.xml.reload" value="true" />
    <constant name="struts.i18n.reload" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <package name="base" extends="struts-default" abstract="true">
        <global-allowed-methods>regex:.*</global-allowed-methods>
    </package>
</struts>

 

struts-book.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <package name="book" extends="base" >
        <action name="/book_*" class="bookAction" method="{1}"></action>
    </package>
</struts>

 

 

 

spring-book.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:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


    <bean class="com.hxc.book.dao.BookDao" parent="baseDao" id="bookDao"></bean>
    <bean class="com.hxc.book.biz.impl.BookBizImpl" parent="baseBiz" id="bookBiz">
        <property name="bookDao" ref="bookDao"></property>
    </bean>
    <bean class="com.hxc.book.web.BookAction" parent="baseAction" id="bookAction">
        <property name="bookBiz" ref="bookBiz"></property>
    </bean>
    

</beans>

 

 

 

spring-context.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:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">



    <import resource="spring-hibernate.xml"/>
    <import resource="spring-book.xml"/>


</beans>

 

 web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <display-name>Archetype Created Web Application</display-name>
    <!-- 1、整合spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 2、整合struts2 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

    <!-- 3、添加过滤器 -->
    <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>
</web-app>

 

测试代码:

技术图片

BaseEntity 
package com.hxc.base.entity;

import java.io.Serializable;

/**
 * 这里面放所有实体类
 *     jsp传递到后台的参数
 *     非数据库与表的映射关系字段属性
 * @author 旧城
 *
 */
public class BaseEntity implements Serializable{

}

 

BaseBiz 
package com.hxc.base.biz;

public class BaseBiz {

}

 

StringUtils 
package com.hxc.base.util;

    public class StringUtils {
        private StringUtils() {
        }
    
       
        public static boolean isBlank(String s) {
            boolean b = false;
            if (null == s || s.trim().equals("")) {
                b = true;
            }
            return b;
        }
        
        
        public static boolean isNotBlank(String s) {
            return !isBlank(s);
        }
    
    }

 

PageBean 
package com.hxc.base.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * ?????????
 *
 */
public class PageBean {

    private int page = 1;// ???

    private int rows = 10;// ???С

    private int total = 0;// ???¼??

    private boolean pagination = true;// ?????
    private Map<String,String[]> paMap=new HashMap<>();
    private String url;
    
    
    
    public void setRequest(HttpServletRequest req) {
        Map<String, String[]> parameterMap = req.getParameterMap();
        StringBuffer url=req.getRequestURL();
        
        //???????????????Я???ò???
        this.setPaMap(req.getParameterMap());
        this.setUrl(req.getRequestURL().toString());
        //??jsp??????????????
        this.setPagination(req.getParameter("pagination"));
        //??jsp????????????????????
        this.setRows(req.getParameter("rows"));
        this.setPage(req.getParameter("page"));
    }
    public void setPage(String page) {
        this.page=StringUtils.isNotBlank(page) ? Integer.valueOf(page) : this.page;
    }
    
    public void setPagination(String pagination) {
        this.pagination=StringUtils.isNotBlank(pagination) ? !"false".equals(pagination):this.pagination;
    }

    public void setRows(String rows) {
        this.rows=StringUtils.isNotBlank(rows) ? Integer.valueOf(rows) : this.rows;
        
    }

    public Map<String, String[]> getPaMap() {
        return paMap;
    }

    public void setPaMap(Map<String, String[]> paMap) {
        this.paMap = paMap;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public PageBean() {
        super();
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public void setTotal(String total) {
        this.total = Integer.parseInt(total);
    }

    public boolean isPagination() {
        return pagination;
    }

    public void setPagination(boolean pagination) {
        this.pagination = pagination;
    }

    /**
     * ????????¼???±?
     * 
     * @return
     */
    public int getStartIndex() {
        return (this.page - 1) * this.rows;
    }

    @Override
    public String toString() {
        return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
    }
    /**
     * ????????????
     * @return
     */
    public int getMaxPage() {
        
        return this.total % this.rows==0 ? this.total / this.rows : this.total / this.rows+1;
    }
    /**
     * ???????
     * @return
     */
    public int getNextPage() {
        
        return this.page < this.getMaxPage() ? this.page+1 : this.page;
    }
    /**
     * ???????
     * @return
     */
    public int getpreviousPage() {
        
        return this.page > 1 ? this.page-1 : this.page;
    }
}

 

BaseAction 

package com.hxc.base.web;

import java.io.Serializable;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

public class BaseAction implements ServletRequestAware, ServletResponseAware,Serializable{
    private static final long serialVersionUID = -7110462505161900879L;
    /**
     * 为了传值使用
     */
    protected HttpServletResponse response;
    protected HttpServletRequest request;
    protected HttpSession session;
    protected ServletContext application;
    
    /**
     * 为了配置跳转页面所用
     */
    protected final static String SUCCESS = "success";
    protected final static String FAIL = "fail";
    protected final static String LIST = "list";
    protected final static String ADD = "add";
    protected final static String EDIT = "edit";
    protected final static String DETAIL = "detail";
    
    /**
     * 具体传值字段    后端向jsp页面传值所用字段
     */
    protected Object result;
    protected Object msg;
    protected int code;

    public Object getResult() {
        return result;
    }

    public Object getMsg() {
        return msg;
    }

    public int getCode() {
        return code;
    }

    @Override
    public void setServletResponse(HttpServletResponse arg0) {
        this.response = arg0;
        
    }

    @Override
    public void setServletRequest(HttpServletRequest arg0) {
        this.request = arg0;
        this.session = arg0.getSession();
        this.application = arg0.getServletContext();
    }

}

 

 

Book 
package com.hxc.book.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Locale.Category;
import java.util.Set;

public class Book implements Serializable {
    
    /**
     * 
     */
    private static final long serialVersionUID = -7562082680913851571L;
    
    private Integer bid;
    private String bname;
    private Float price;
    public Integer getBid() {
        return bid;
    }
    public void setBid(Integer bid) {
        this.bid = bid;
    }
    public String getBname() {
        return bname;
    }
    public void setBname(String bname) {
        this.bname = bname;
    }
    public Float getPrice() {
        return price;
    }
    public void setPrice(Float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
    }
    public Book(Integer bid, String bname, Float price) {
        super();
        this.bid = bid;
        this.bname = bname;
        this.price = price;
    }
    public Book() {
        super();
        // TODO Auto-generated constructor stub
    }
    
}

 

 book.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class table="t_mvc_book" name="com.hxc.book.entity.Book" >
        <id name="bid" type="java.lang.Integer" column="bid">
            <generator class="increment"></generator>
        </id>
        
        <property name="bname" type="java.lang.String" column="bname">
        </property>
        <property name="price" type="java.lang.Float" column="price">
        </property>
    </class>
</hibernate-mapping>

 

 BookBiz 

package com.hxc.book.biz;

import java.util.List;

import com.hxc.book.entity.Book;

public interface BookBiz {

    public int add(Book book);

    public void edit(Book book);

    public void del(Book book);

    public List<Book> list();
}
BookBizImpl 
package com.hxc.book.biz.impl;

import java.util.List;

import com.hxc.book.biz.BookBiz;
import com.hxc.book.dao.BookDao;
import com.hxc.book.entity.Book;

public class BookBizImpl implements BookBiz{

    private BookDao bookDao;
    
    public BookDao getBookDao() {
        return bookDao;
    }

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

    @Override
    public int add(Book book) {
        return bookDao.add(book);
    }

    @Override
    public void edit(Book book) {
        bookDao.edit(book);
    }

    @Override
    public void del(Book book) {
        bookDao.del(book);
    }

    @Override
    public List<Book> list() {
        return bookDao.list();
    }

}

 

BookDao 
package com.hxc.book.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import com.hxc.base.dao.BaseDao;
import com.hxc.book.entity.Book;
/**
 * 注意:
 * 
 *     1,一定要继承BaseDao(是为了hibernateTemplete)
 *     2,方法命名有讲究(一定要符合声明事务所定义的规则)
 *         若是不遵循规则,那么数据是不会提交到数据库的
 *     3,hibernateTemplate模板是在执行查询的时候比较特殊
 * @author 旧城
 *
 */
public class BookDao extends BaseDao{

    public int add(Book book) {
        return (int) getHibernateTemplate().save(book);
    }
    
    public void edit(Book book) {
        getHibernateTemplate().update(book);
    }
    
    public void del(Book book) {
        getHibernateTemplate().delete(book);
    }
    
    public List<Book> list() {
        return (List<Book>) getHibernateTemplate().execute(new HibernateCallback<List<Book>>() {

            @Override
            public List<Book> doInHibernate(Session session) throws HibernateException {
                // TODO Auto-generated method stub
                return session.createQuery("from Book").list();
            }
        });
    }
}

 

BookAction 
package com.hxc.book.web;

import java.util.List;

import com.hxc.base.web.BaseAction;
import com.hxc.book.biz.BookBiz;
import com.hxc.book.entity.Book;
import com.opensymphony.xwork2.ModelDriven;

public class BookAction extends BaseAction implements ModelDriven<Book>{

    private Book book=new Book();
    private BookBiz bookBiz;
    
    
    public BookBiz getBookBiz() {
        return bookBiz;
    }


    public void setBookBiz(BookBiz bookBiz) {
        this.bookBiz = bookBiz;
    }


    @Override
    public Book getModel() {
        // TODO Auto-generated method stub
        return book;
    }
    
    public String add() {
        System.out.println(book);
        this.bookBiz.add(book);
        return null;
    }
    
    public String edit() {
        System.out.println(book);
        this.bookBiz.add(book);
        return null;
    }
    public String del() {
        System.out.println(book);
        this.bookBiz.add(book);
        return null;
    }
    
    public String list() {
        List<Book> list2=this.bookBiz.list();
        for (Book book : list2) {
            System.out.println(book);
        }
        return null;
    }
    
}

 

运行:

技术图片

 

BookBiz 

SSH整合

标签:created   let   ||   break   list()   未使用   encoding   pom   c3p0连接池   

原文地址:https://www.cnblogs.com/huxiaocong/p/11370797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!