搭建Jquery+SpringMVC+Spring+Hibernate+MySQL平台

1. 费用条件

搭建SpringMVC+Spring+Hibernate平台,springmvchibernate

一. 支出条件

  1. 点击此查看并下载需求的 Eclipse IDE for Java EE
Developers 开发工具,推荐选用叁拾肆位

    二. 点击此查看并下载供给的 MySQL Server 数据库,推荐选取叁16个人

  三. 点击此找到并下载  Java SE Development Kit 6u四伍,推荐采用30位

  四. 点击此找到并下载  apache-tomcat-6.0.4八.zip

   

贰. 准备工作

  1. 点击此找到并下载
spring-framework-肆.三.四.RELEASE-dist.zip,解压压缩合并在 libs
文件夹下得到:   

图片 1

spring-aop-4.3.4.RELEASE.jar
spring-beans-4.3.4.RELEASE.jar
spring-context-4.3.4.RELEASE.jar
spring-core-4.3.4.RELEASE.jar
spring-expression-4.3.4.RELEASE.jar
spring-jdbc-4.3.4.RELEASE.jar
spring-orm-4.3.4.RELEASE.jar
spring-tx-4.3.4.RELEASE.jar
spring-web-4.3.4.RELEASE.jar
spring-webmvc-4.3.4.RELEASE.jar

View Code

    如今最高版本

 

  二. 点击此找到并下载 aspectjweaver-一.八.玖.jar 

    近期最高稳定版本,spring AOP 依赖 aspectj 来贯彻的

  3. 点击此找到并下载 hibernate-release-4.2.贰壹.Final.zip,解压缩并在
libs/required 文件夹下获得:

图片 2

antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.21.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar

View Code

    支持 java 壹.陆 的最高版本

 

  4. 点击此找到并下载 slf四j-一.7.二一.zip,解压缩得到:

图片 3

jcl-over-slf4j-1.7.21.jar
slf4j-api-1.7.21.jar
slf4j-log4j12-1.7.21.jar

View Code

    近年来最高版本,spring 的日记记录选用:jc-over-slf四j —> slf四j
—> log四j

 

  五. 点击此找到并下载 log四j-一.贰.1七.jar 

    协助 java 一.⑥、spring-4.3.四 的万丈稳定版本

 

  6. 点击此找到并下载
log④jdbc四-一.二.壹.jar.zip,解压缩获得:log四jdbc4-一.二.1.jar

  7. 点击此找到并下载 fastjson-一.二.二1.jar

  8. 点击此找到并下载
mysql-connector-java-五.1.40.zip,解压缩获得: mysql-connector-java-5.一.40-bin.jar

  九. 点击此找到并下载 commons-lang3-叁.五.jar

    近年来最高版本

叁. 工程搭建

  一. Eclipse –> File –> New –> Dynamic Web Project –>
输入工程名 ims –> Next –>

    修改 Default output folder 为:WebContent/WEB-INF/classes –>
Finish

 

  二. 将(一)中获取的兼具jar包放到 WebContent/WEB-INF/lib 文件夹下

 

  三. src 目录下创立如下包结构:    

图片 4

src
 |--com
 |   |--ims
 |   |   |--common
 |   |   |--persistence
 |   |   |       |--base
 |   |   |       |--dao
 |   |   |       |   |--xxx
 |   |   |       |       |--impl
 |   |   |       |--model
 |   |   |            |--xxx
 |   |   |--service
 |   |   |     |--xxx
 |   |   |         |--impl
 |   |   |--web
 |   |   |   |--controller
 |   |   |   |      |---xxx

View Code

    当中,xxx表示子项目

 

  4. src 目录下创办如下文件:

    applicationContext.xml

图片 5

<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/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">  
    <context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="aspectj" expression="com.ims.persistence.dao..*.impl.*DaoImpl"/>
        <context:include-filter type="aspectj" expression="com.ims.service..*.impl.*BSImpl"/>
    </context:component-scan>   

    <!-- log4jdbc,需要依赖slf4j框架,拦截输出完整sql语句 -->
    <bean id="log4jdbcInterceptor" class="net.sf.log4jdbc.DataSourceSpyInterceptor" />
    <bean id="dataSourceLog4jdbcAutoProxyCreator"
        class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="interceptorNames">
            <list>
                <value>log4jdbcInterceptor</value>
            </list>
        </property>
        <property name="beanNames">
            <list>                
                <value>sysDatasource</value>
                <value>mmsDatasource</value>
            </list>
        </property>
    </bean>
</beans>

View Code

    

    applicationContextXxx.xml

图片 6

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

    <bean id="xxxDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />        
        <property name="url" value="jdbc:mysql://localhost:3306/xxx?characterEncoding=utf8" />        
        <property name="username" value="root" />        
        <property name="password" value="123456" />    
    </bean>

    <bean id="xxxSessionFactory" 
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">    
          <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <property name="dataSource" ref="xxxDatasource" />                                                    
        <property name="packagesToScan">
            <list>
                <value>com.ims.persistence.model.xxx</value>
            </list>    
        </property>        
    </bean>

    <bean id="xxxTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="xxxSessionFactory"/>
    </bean>

    <tx:advice id="xxxTxAdvice" transaction-manager="xxxTransactionManager">   
        <tx:attributes>   
            <tx:method name="find*" isolation="READ_COMMITTED" read-only="true"/>
            <tx:method name="get*" isolation="READ_COMMITTED" read-only="true"/>
            <tx:method name="*" isolation="READ_COMMITTED" rollback-for="Throwable" />
        </tx:attributes>   
    </tx:advice>

    <aop:config>   
        <aop:pointcut id="xxxTxPointcut" expression="execution(* com.ims.service.xxx.impl..*BSImpl.*(..))"/>   
        <aop:advisor advice-ref="xxxTxAdvice" pointcut-ref="xxxTxPointcut" order="0"/>   
    </aop:config>   

    <bean id="xxxBaseDao" class="com.ims.persistence.dao.xxx.impl.XxxBaseDaoImpl">
        <property name="sessionFactory" ref="xxxSessionFactory"/>
    </bean> 

</beans>

View Code

    在那之中,xxx表示子项目标称呼

    

    controllerServlet.xml

图片 7

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

    <mvc:annotation-driven />
    <context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="aspectj" expression="com.ims.web.controller..*Controller"/>
    </context:component-scan>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/view/" />
    </bean>
</beans>

View Code

    

    hibernate.cfg.xml

图片 8

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>        
        <property name="hibernate.order_updates">true</property>        
        <property name="hibernate.show_sql">false</property>
        <!-- none -->
        <property name="hibernate.hbm2ddl.auto">update</property>        

        <property name="hibernate.c3p0.max_size">30</property>   
         <property name="hibernate.c3p0.min_size">5</property>    
         <property name="hibernate.c3p0.timeout">3000</property>
         <property name="hibernate.c3p0.max_statements">50</property>         
        <!--每隔多少秒检测连接是否可正常使用  -->    
        <property name="c3p0.idle_test_period">121</property>  
        <!--当池中的连接耗尽的时候,一次性增加的连接数量,默认为3-->    
        <property name="c3p0.acquire_increment">1</property>  
        <property name="c3p0.validate">true</property>

        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    </session-factory>

</hibernate-configuration>

View Code

    

    log4j.properties

图片 9

#输出级别和输出位置 ; 包中只有级别大于或等于配置级别,才允许输出
log4j.rootLogger=WARN,console,roll

#控制台输出
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n

#按日期滚动输出
log4j.appender.roll=org.apache.log4j.DailyRollingFileAppender
log4j.appender.roll.File=${catalina.base}/logs/ims/ims.log
log4j.appender.roll.layout=org.apache.log4j.PatternLayout
log4j.appender.roll.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}    %p    %t    %c    %m%n

#继承rootLogger的输出位置
log4j.logger.com.ims = WARN
log4j.logger.org.hibernate.cache = ERROR
log4j.logger.org.directwebremoting = ERROR
#显示sql语句的参数
#log4j.logger.org.hibernate.type=trace 

log4j.logger.jdbc.connection=OFF
log4j.logger.jdbc.audit=OFF
log4j.logger.jdbc.resultset=OFF
log4j.logger.jdbc.sqlonly=OFF
#INFO、OFF
log4j.logger.jdbc.sqltiming=INFO

View Code

 

  5. 创立基础controller类:

    创设工程的底蕴controller类:

      详见 springMVC基础controller类

    成立子项目标根基controller类:

图片 10

package com.ims.web.controller.xxx;

import com.ims.web.controller.BaseController;

public class XxxBaseController extends BaseController{

}

View Code

  六. 创建基础dao类:

    成立工程的基本功dao类:

      详见 hibernate基础dao类

    成立子项指标根基dao类:

      基础接口类:XxxBaseDao.java

图片 11

package com.ims.persistence.dao.xxx;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import com.ims.persistence.base.BaseDao;

/**
 * 统一数据访问接口
 */
public interface XxxBaseDao<T extends Serializable> extends BaseDao<T> {

}

View Code

      基础接口落成类:XxxBaseDaoImpl.java

图片 12

package com.ims.persistence.dao.xxx.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;

import com.ims.persistence.base.BaseDaoImpl;
import com.ims.persistence.dao.xxx.XxxBaseDao;

public class XxxBaseDaoImpl<T extends Serializable> extends BaseDaoImpl<T> implements XxxBaseDao<T>{    
    @Resource(name = "xxxSessionFactory")  
    public void setSuperSessionFactory(SessionFactory xxxSessionFactory) {  
        super.setSessionFactory(xxxSessionFactory);  
    }

}

View Code

 

  7. WebContent 目录下创办如下目录结构:

图片 13

WebContent
    |--common
    |--content
    |     |--css
    |     |--images
    |     |--js
    |--sql
    |   |--xxx
    |--view
    |   |--xxx
    |--viewModel
    |      |--xxx

View Code

  

  8. 修改 WebContent/WEB-INF/web.xml 为:

图片 14

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd 
        http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    version="2.4">
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            classpath:applicationContext.xml,
            classpath:applicationContextXxx.xml
    </param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>webapp.root</param-value>
  </context-param>

  <listener>   
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
  </listener>

  <filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:controllerServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>controller</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

View Code

 

http://www.bkjia.com/Javabc/1178334.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javabc/1178334.htmlTechArticle搭建SpringMVC+Spring+Hibernate平台,springmvchibernate
1. 开发环境 1. 点击此 查看并下载必要的Eclipse IDE for Java EE
Developers开发工具,推荐选取30个人…

  1. 点击此翻开并下载须要的 Eclipse
IDE for Java EE Developers 开发工具,推荐采取③十二位

    2. 点击此查看并下载需求的
MySQL Server 数据库,推荐选取310个人

  3. 点击此找到并下载
 Java SE Development Kit 陆u四伍,推荐采纳3九位

  4. 点击此找到并下载
 apache-tomcat-6.0.4八.zip,兼容3一人和陆拾位版本

  5. 点击此下载
ims 工程文件

 

二. 工程搭建

  1. Eclipse –> File –> New –> Dynamic Web Project –>
输入工程名 ims –> Next –>

    修改 Default output folder 为:WebContent/WEB-INF/classes –>
Finish

  2. 将下载的工程文件按目录复制到 ims 工程中

  注:ims全称:information management
system

 

3. 工程目录结构介绍

  注:以下的xxx均代表子项目名称,如:

    子项目 sys
全称:system,基础消息、权限管理体系

    子项目 mms 全称:material
management system,材质管理体系

    子项目 iot 全称:Internet of
things,物联网系统

 

图片 15图片 16

src
 |--com
 |   |--ims
 |   |   |--common
 |   |   |--persistence
 |   |   |       |--base
 |   |   |       |--dao
 |   |   |       |   |--xxx
 |   |   |       |       |--impl
 |   |   |       |--model
 |   |   |            |--xxx
 |   |   |--service
 |   |   |     |--xxx
 |   |   |         |--impl
 |   |   |--web
 |   |   |   |--controller
 |   |   |   |      |---xxx


WebContent
    |--common
    |--content
    |     |--css
    |     |--images
    |     |--js
    |--sql
    |   |--xxx
    |--view
    |   |--xxx
    |--viewModel
    |      |--xxx

View Code

  

四. jar包介绍

  1. spring-framework-4.3.4.RELEASE,可点击此下载并在
libs 文件夹下得到: 

图片 17图片 18

spring-aop-4.3.4.RELEASE.jar
spring-beans-4.3.4.RELEASE.jar
spring-context-4.3.4.RELEASE.jar
spring-core-4.3.4.RELEASE.jar
spring-expression-4.3.4.RELEASE.jar
spring-jdbc-4.3.4.RELEASE.jar
spring-orm-4.3.4.RELEASE.jar
spring-tx-4.3.4.RELEASE.jar
spring-web-4.3.4.RELEASE.jar
spring-webmvc-4.3.4.RELEASE.jar

View Code

  2. aspectjweaver-壹.八.玖.jar,spring AOP 依赖 aspectj
来兑现的,可点击此下载 

  叁. jackson-二.三.0,,援救 spring-四.三.肆 的最低版本,可点击此下载

图片 19图片 20

jackson-annotations-2.3.0.jar
jackson-core-2.3.0.jar
jackson-databind-2.3.0.jar

View Code

 

  肆. slf四j-一.7.贰1,spring 的日记记录采取:jc-over-slf4j —> slf四j
—> log四j,可点击此下载得到:

图片 21图片 22

jcl-over-slf4j-1.7.21.jar
slf4j-api-1.7.21.jar
slf4j-log4j12-1.7.21.jar

View Code

  伍. log四j-一.二.17.jar,协助 java 一.陆、spring-四.3.4的万丈稳定版本,可点击此下载  

  6. log四jdbc4-一.二.壹.jar,jdbc层日志框架,可点击此下载

 

  7. hibernate-release-四.2.贰一.Final,支持 java 1.6的参天版本,可点击此下载并在
libs/required 文件夹下获得:

图片 23图片 24

antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.21.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar

View Code

  8. mysql-connector-java-5.1.40-bin.jar,mysql驱动包,可点击此下载

 

  9. fastjson-1.2.21.jar

  10. commons-lang3-3.5.jar

伍. 配置文件介绍

  1. applicationContext.xml

图片 25图片 26

<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/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">  
    <context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="aspectj" expression="com.ims.persistence.dao..*.impl.*DaoImpl"/>
        <context:include-filter type="aspectj" expression="com.ims.service..*.impl.*BSImpl"/>
    </context:component-scan>   

    <!-- log4jdbc,需要依赖slf4j框架,拦截输出完整sql语句 -->
    <bean id="log4jdbcInterceptor" class="net.sf.log4jdbc.DataSourceSpyInterceptor" />
    <bean id="dataSourceLog4jdbcAutoProxyCreator"
        class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="interceptorNames">
            <list>
                <value>log4jdbcInterceptor</value>
            </list>
        </property>
        <property name="beanNames">
            <list>                
                <value>xxxDatasource</value>
            </list>
        </property>
    </bean>
</beans>

View Code

  2. applicationContextXxx.xml

图片 27图片 28

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

    <bean id="xxxDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />        
        <property name="url" value="jdbc:mysql://localhost:3306/xxx?characterEncoding=utf8" />        
        <property name="username" value="root" />        
        <property name="password" value="123456" />    
    </bean>

    <bean id="xxxSessionFactory" 
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">    
          <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <property name="dataSource" ref="xxxDatasource" />                                                    
        <property name="packagesToScan">
            <list>
                <value>com.ims.persistence.model.xxx</value>
            </list>    
        </property>        
    </bean>

    <bean id="xxxTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="xxxSessionFactory"/>
    </bean>

    <tx:advice id="xxxTxAdvice" transaction-manager="xxxTransactionManager">   
        <tx:attributes>   
            <tx:method name="find*" isolation="READ_COMMITTED" read-only="true"/>
            <tx:method name="get*" isolation="READ_COMMITTED" read-only="true"/>
            <tx:method name="*" isolation="READ_COMMITTED" rollback-for="Throwable" />
        </tx:attributes>   
    </tx:advice>

    <aop:config>   
        <aop:pointcut id="xxxTxPointcut" expression="execution(* com.ims.service.xxx.impl..*BSImpl.*(..))"/>   
        <aop:advisor advice-ref="xxxTxAdvice" pointcut-ref="xxxTxPointcut" order="0"/>   
    </aop:config>   

    <bean id="xxxBaseDao" class="com.ims.persistence.dao.xxx.impl.XxxBaseDaoImpl">
        <property name="sessionFactory" ref="xxxSessionFactory"/>
    </bean> 

</beans>

View Code

  3. controllerServlet.xml

图片 29图片 30

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

    <mvc:annotation-driven />
    <context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="aspectj" expression="com.ims.web.controller..*Controller"/>
    </context:component-scan>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/view/" />
    </bean>
</beans>

View Code

  4. hibernate.cfg.xml

图片 31图片 32

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>        
        <property name="hibernate.order_updates">true</property>        
        <property name="hibernate.show_sql">false</property>
        <!-- none -->
        <property name="hibernate.hbm2ddl.auto">update</property>        

        <property name="hibernate.c3p0.max_size">30</property>   
         <property name="hibernate.c3p0.min_size">5</property>    
         <property name="hibernate.c3p0.timeout">3000</property>
         <property name="hibernate.c3p0.max_statements">50</property>         
        <!--每隔多少秒检测连接是否可正常使用  -->    
        <property name="c3p0.idle_test_period">121</property>  
        <!--当池中的连接耗尽的时候,一次性增加的连接数量,默认为3-->    
        <property name="c3p0.acquire_increment">1</property>  
        <property name="c3p0.validate">true</property>

        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    </session-factory>

</hibernate-configuration>

View Code

  5. log4j.properties

图片 33图片 34

#输出级别和输出位置 ; 包中只有级别大于或等于配置级别,才允许输出
log4j.rootLogger=WARN,console,roll

#控制台输出
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n

#按日期滚动输出
log4j.appender.roll=org.apache.log4j.DailyRollingFileAppender
log4j.appender.roll.File=${catalina.base}/logs/ims/ims.log
log4j.appender.roll.layout=org.apache.log4j.PatternLayout
log4j.appender.roll.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}    %p    %t    %c    %m%n

#继承rootLogger的输出位置
log4j.logger.com.ims = WARN
log4j.logger.org.hibernate.cache = ERROR
log4j.logger.org.directwebremoting = ERROR
#显示sql语句的参数
#log4j.logger.org.hibernate.type=trace 

log4j.logger.jdbc.connection=OFF
log4j.logger.jdbc.audit=OFF
log4j.logger.jdbc.resultset=OFF
log4j.logger.jdbc.sqlonly=OFF
#INFO、OFF
log4j.logger.jdbc.sqltiming=INFO

View Code

  6. web.xml

图片 35图片 36

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd 
        http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    version="2.4">
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            classpath:applicationContext.xml,
            classpath:applicationContextXxx.xml
    </param-value>
  </context-param>

  <listener>   
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

  <filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:controllerServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>controller</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

View Code

  

6. 类文件介绍

  1. 基础controller类

    功效:设置请求、响应对象;session、cookie操作;ajax访问回到json数据;

    

    一.一. BaseController.java,工程的基础controller类

图片 37图片 38

图片 39

package com.ims.web.controller;
import java.io.IOException;
import java.net.URLDecoder;

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

import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class BaseController {
    /**
     *  AJAX访问返回操作成功状态标识符
     */
    protected static final String STATUS_SUCCESS = "success";
    /**
     *  AJAX访问返回操作失败状态标识符
     */
    protected static final String STATUS_ERROR = "error";

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    /**
     * 每个controller方法执行前被执行
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request,
            HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    /**
     * 取得session中的值
     * @param name session主键
     * @return 主键对应的值
     */
    public Object getSession(String name) {
        return session.getAttribute(name);
    }

    /**
     * 往session中添加键值对
     * @param name session主键
     * @param obj session值
     */
    public void setSession(String name, Object obj) {
        session.setAttribute(name, obj);
    }

    /**
     * 添加cookie
     * @param key cookie主键
     * @param value cookie值
     */
    public void addCookie(String key, String value){
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");// 这个要设置  
        cookie.setMaxAge(60*60*24*30);//保留一个月 以秒为单位  
        response.addCookie(cookie);
    }

    /**
     * 删除cookie
     * @param key cookie主键
     */
    public void deleteCookie(String key){
        Cookie cookies[] = request.getCookies();  
        if (cookies != null) {  
            for (int i = 0; i < cookies.length; i++) {  
                if (cookies[i].getName().equals(key)) {  
                    Cookie cookie = new Cookie(key,null);
                    cookie.setPath("/");//设置成跟写入cookies一样的  
                    cookie.setMaxAge(0);  
                    response.addCookie(cookie);  
                }  
            }  
        }  
    }

    /**
     * 取得cookie的值
     * @param key cookie主键
     */
    public String getCookieValue(String key) {
        String cookieVal = null;
        for(Cookie cookie : request.getCookies()){
            if (cookie.getName().equals(key)) {   
                try {
                    cookieVal = URLDecoder.decode(cookie.getValue(), "UTF-8");
                } catch (Exception e) {} 
                break;
            }  
        }
        return cookieVal;
    }

    /**
     * 取得访问项目的url
     */
    public String getBaseUrl(){
        return request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() ;
    }

    /**
     * ajax输出
     * @param content 输出的文本内容
     * @param type 输出的文本类内容
     */
    public void ajax(String content, String type) {
        try {
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 响应json格式的字符串
     * @param content json格式的字符串
     */
    public void ajax(String content) {
        ajax(content, "application/json");
    }

    /**
     * 响应带状态的json格式的数据
     * @param status
     * @param content
     */
    public void ajaxJson(String status, Object content){
        String json = "{\"status\" : \""+status+"\", " +
                "\"message\" : "+JSON.toJSONString(content)+" }";
        ajax(json, "application/json");
    }

    /**
     * 响应json格式的数据
     * @param content
     */
    public void ajaxJson(Object content) {    
        String json = JSON.toJSONString(content, SerializerFeature.WriteDateUseDateFormat);
        ajax(json, "application/json");
    }

}

图片 40

View
Code

    一.2. XxxBaseController.java,子项指标功底controller类:

图片 41图片 42

package com.ims.web.controller.xxx;

import com.ims.web.controller.BaseController;

public class XxxBaseController extends BaseController{

}

View Code

  

  2. 基础dao类

    功用:数据库的保存、更新、删除;sql、hql查询;分页查询;调用存款和储蓄进度

 

    2.一. 工程的功底dao类

      BaseDao.java

图片 43图片 44

package com.ims.persistence.base;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;

/**
 * 统一数据访问接口
 */
public interface BaseDao<T extends Serializable> {

    /**
     * 保存实体对象
     * @param entity 实体对象
     */
    public void save(T entity); 

    /**
     * 更新实体对象
     * @param 实体对象
     */
    public void update(T entity);

    /**
     * 保存或更新实体对象
     * @param entity 实体对象
     */
    public void saveOrUpdate(T entity);

    /**
     * 删除实体对象
     * @param entity 实体对象
     */
    public void delete(T entity);

    /**
     * 查询hql语句,返回唯一结果
     * @param hql 
     */
    public Object findUniqueResult(String hql); 

    /**
     * 执行sql语句,更新数据库
     * @param sql
     */
    public void updateBySql(String sql);

    /**
     * 通过Criteria对象查询,返回实体对象结果集
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集
     */
    public List findByCriteria(DetachedCriteria detachedCriteria);

    /**
     * 通过sql语句查询,返回map对象结果集
     * @param sql 
     * @return map对象结果集
     */
    public List<Map<String, Object>> findBySql(String sql);

    /**
     * 查询sql语句,返回唯一结果
     * @param sql 
     */
    public Object findUniqueResultBySql(String sql);

    /**
     * 通过Criteria对象查询,返回结果集的记录数
     * @param detachedCriteria 离线的Criteria对象
     * @return 结果集的记录数
     */
    public long getCount(DetachedCriteria detachedCriteria);

    /**
     * 通过Criteria对象进行分页查询,返回实体对象结果集
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集 
     */
    public List<T> findPage(int pageNum, int pageSize, DetachedCriteria detachedCriteria);

    /**
     * 通过sql语句,进行分页查询,返回分页对象
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param sql
     * @return 分页对象
     */
    public Pagination findPage(int pageNum, int pageSize, String sql); // 查找分页对象列表

    /**
     * 调用存储过程,返回单结果集
     * @param proceName 存储过程名称
     * @param params 输入参数集合
     * @return map对象结果集
     */
    public List<Map<String, Object>> callProcedure(String proceName, final List<Object> params);
}

View Code

      BaseDaoImpl.java

图片 45图片 46

package com.ims.persistence.base;

import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.jdbc.Work;

public class BaseDaoImpl<T extends Serializable> implements BaseDao<T>{          

    private SessionFactory sessionFactory;

    public BaseDaoImpl(){
        super();
    }


    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }


    /**
     * 返回数据库session对象
     * @return
     */
    protected Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    /**
     * 保存实体对象
     * @param entity 实体对象
     */
    @Override
    public void save(T entity){
        Session session = getSession();
        session.save(entity);        
        session.flush();
        session.evict(entity);
    }

    /**
     * 更新实体对象
     * @param 实体对象
     */
    @Override
    public void update(T entity){
        Session session = getSession();
        session.update(entity);        
        session.flush();
        session.evict(entity);
    }

    /**
     * 保存或更新实体对象
     * @param entity 实体对象
     */
    @Override
    public void saveOrUpdate(T entity) {        
        Session session = getSession();
        session.saveOrUpdate(entity);        
        session.flush();
        session.evict(entity);    
    }

    /**
     * 删除实体对象
     * @param entity 实体对象
     */
    @Override
    public void delete(T entity){
        Session session = getSession();
        session.delete(entity);        
        session.flush();
        session.evict(entity);
    }    

    /**
     * 查询hql语句,返回唯一结果
     * @param hql 
     */
    @Override
    public Object findUniqueResult(String hql){
        Query query = getSession().createQuery(hql);
        return query.uniqueResult();
    }

    /**
     * 执行sql语句,更新数据库
     * @param sql
     */
    @Override
    public void updateBySql(final String sql){
        getSession().doWork(new Work() {   
            @Override
            public void execute(Connection connection) throws SQLException {
                connection.prepareStatement(sql).executeUpdate();
            }
        });
    }    

    /**
     * 通过Criteria对象查询,返回实体对象结果集
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集
     */
    @Override
    public List findByCriteria(DetachedCriteria detachedCriteria){
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        List records = criteria.list();
        return records;
    }

    /**
     * 通过sql语句查询,返回map对象结果集
     * @param sql 
     * @return map对象结果集
     */
    @Override
    public List<Map<String, Object>> findBySql(final String sql){
        final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        getSession().doWork(new Work() {   
            @Override
            public void execute(Connection connection) throws SQLException {
                ResultSet rs = connection.prepareStatement(sql).executeQuery();
                result.addAll(RsHelper.rSToList(rs));
            }
        });
        return result;
    }

    /**
     * 查询sql语句,返回唯一结果
     * @param sql 
     */
    @Override
    public Object findUniqueResultBySql(String sql) {    
        return getSession().createSQLQuery(sql.toString()).uniqueResult();
    }

    /**
     * 通过Criteria对象查询,返回结果集的记录数
     * @param detachedCriteria 离线的Criteria对象
     * @return 结果集的记录数
     */
    @Override
    public long getCount(DetachedCriteria detachedCriteria) {
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        Object object = criteria.setProjection(Projections.rowCount()).uniqueResult();
        criteria.setProjection(null);
        Long totalRow = Long.valueOf(String.valueOf(object));
        return totalRow;
    }

    /**
     * 通过Criteria对象进行分页查询,返回实体对象结果集
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集 
     */
    @Override
    public List<T> findPage(int pageNum, int pageSize, 
            DetachedCriteria detachedCriteria){
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        List<T> records = criteria.setFirstResult((pageNum-1) * pageSize).setMaxResults(pageSize).list();
        return records;
    }

    /**
     * 通过sql语句,进行分页查询,返回分页对象
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param sql
     * @return 分页对象
     */
    @Override
    public Pagination findPage(final int pageNum, final int pageSize,final String sql){
        final Pagination page = new Pagination();
        getSession().doWork(new Work() {   
            @Override
            public void execute(Connection connection) throws SQLException {
                String countSql = MessageFormat.format("select count(*) from ({0}) page", sql);
                ResultSet rs = connection.prepareStatement(countSql).executeQuery();
                page.setTotal(Long.valueOf(RsHelper.getUniqueResult(rs).toString()));

                long firstResult = (pageNum - 1)*pageSize;
                String selectSql = MessageFormat.format("select * from ({0}) page limit {1},{2}", sql, firstResult, firstResult+pageSize);
                page.setRows(RsHelper.rSToList(connection.prepareStatement(selectSql).executeQuery()));
            }
        });

        return