开发者社区> 文艺小青年> 正文

struts2.3.24 + spring4.1.6 + hibernate4.3.11+ mysql5.5.25开发环境搭建及相关说明

简介:
+关注继续查看

 一、目标

1、搭建传统的ssh开发环境,并成功运行(插入、查询)

2、了解c3p0连接池相关配置

3、了解验证hibernate的二级缓存,并验证

4、了解spring事物配置,并验证

5、了解spring的IOC(依赖注入),将struts2的action对象(bean)交给spring管理,自定义bean等...并验证

6、了解spring aop(面向切面编程),并编写自定义切面函数,验证结果

二、前期准备

开发环境:eclipse for java ee;mysql5.5.25;jdk1.7.0_79;navicat10.1.7(可选);

创建数据库demo:

复制代码
/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50519
Source Host           : localhost:3306
Source Database       : demo

Target Server Type    : MYSQL
Target Server Version : 50519
File Encoding         : 65001

Date: 2016-01-09 23:36:02
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `account` varchar(200) NOT NULL,
  `name` varchar(200) NOT NULL,
  `address` varchar(1000) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

复制代码

新建web工程,目录结构如下:

jar包准备,放到WEB-INF的lib目录下(有兴趣的可以用maven管理过程,但是有时候下载jar包很慢...)

相关jar包都可以在下载下来的struts、spring、hibernate中找到,这里给个参考,有些是可以删除的,比如spring mvc部分的jar包:

三、配置web.xml

  • 配置一个struts2的filter,映射所有*.action请求,由StrutsPrepareAndExecuteFilter对象来处理;
  • 配置context-param参数,指定spring配置文件的路径,<context-param>中的参数可以用ServletContext.getInitParameter(“param-name”)来获取;
  • 配置listener,主要是读取applicationContext.xml配置文件信息,创建bean等初始化工作;
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSH</display-name>

  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>*.action</url-pattern>
  </filter-mapping>

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

  <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>
复制代码

四、配置applicationContext.xml

  • 配置自动扫描ssh包下的@Repostory,@Service等注解,并生成对应的bean;
  • 配置数据源(jdbc连接池为c3p0,可以参考c3p0的详细配置),连接池主要作用是快速提供connection,重复利用,不需要每次销毁创建,需配置用户名、密码、最大连接数、最小连接数、初始连接数等相关参数;
  • 配置sessionFactory(可以参考hibernate的详细配置,这里配置开启二级缓存),主要作用是提供session,执行sql语句;这里我们将会通过HibernateTemplate来对数据库进行操作,方便spring进行实物控制;ps,hibernate配置中还要配置类与数据库表的映射;
  • 配置事务管理器bean为HibernateTransactionManager,并把成员属性sessionFactory初始化为之前配置的sessionFactory bean;
  • 配置事务的传播特性,并配置一个切面引用它,对所有ssh.service包及子包下所有add、delete、update、save方法进行事务控制,还可以配置事务传播行为等参数;
  • 最后是一个自定义aop相关配置,对ssh.aop.AopTest下所有test开头的方法应用自定义切面‘myAop’进行控制,后续会验证结果;
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       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.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    
    <!-- scans the classpath for annotated components (including @Repostory 
    and @Service  that will be auto-registered as Spring beans  -->          
    <context:component-scan base-package="ssh" />

    <!--配数据源 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo" />
        <property name="user" value="root" />
        <property name="password" value="root" />
        
        <property name="acquireIncrement" value="1"></property>  
        <property name="initialPoolSize" value="80"></property>  
        <property name="maxIdleTime" value="60"></property>  
        <property name="maxPoolSize" value="80"></property>  
        <property name="minPoolSize" value="30"></property>  
        <property name="acquireRetryDelay" value="1000"></property>  
        <property name="acquireRetryAttempts" value="60"></property>  
        <property name="breakAfterAcquireFailure" value="false"></property>
        <!-- 如出现Too many connections, 注意修改mysql的配置文件my.ini,增大最多连接数配置项,(查看当前连接命令:show processlist) -->
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="current_session_context_class">thread</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
            </props>
        </property>
        <property name="mappingLocations"> 
            <list> 
              <value>classpath:ssh/model/User.hbm.xml</value> 
            </list> 
        </property> 
        <!--  
        <property name="annotatedClasses">
            <list>
                <value>ssh.model.User</value>
            </list>
        </property>
        -->
    </bean>
    
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <!-- 事务的传播特性 -->
    <tx:advice id="txadvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
        </tx:attributes>
    </tx:advice>
    

    <aop:config>
        <aop:pointcut id="pcMethod" expression="execution(* ssh.service..*.*(..))" />
        <aop:advisor pointcut-ref="pcMethod" advice-ref="txadvice" />
    </aop:config>
      
   <!-- 自定义aop处理 测试 -->
   <bean id="aopTest" class="ssh.aop.AopTest"></bean>
   <bean id="myAop" class="ssh.aop.MyAop"></bean>
   <aop:config proxy-target-class="true">
        <aop:aspect ref="myAop">
            <aop:pointcut id="pcMethodTest" expression="execution(* ssh.aop.AopTest.test*(..))"/>
            <aop:before pointcut-ref="pcMethodTest" method="before"/>
            <aop:after pointcut-ref="pcMethodTest" method="after"/>
        </aop:aspect>
    </aop:config>

 </beans>
复制代码

 五、配置struts.xml

配置struts.objectFactory常数为spring,表示action由通过spring的bean中获取;

配置result type为"json",也可以配置其它的,这里为了前后端数据交互简便,配置成json格式;

配置两个action,addUser和queryAllUser;

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.objectFactory" value="spring"/>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />

    <package name="default" extends="struts-default,json-default">


          <global-results>
              <result type="json">
                <param name="root">json</param>
                <param name="contentType">text/html</param>
              </result>
         </global-results> 

                <action name="addUser" class="userAction" method="addUser">
                    <result>.</result>
                </action>
                
                <action name="queryAllUser" class="userAction" method="queryAllUser">
          <result>.</result>
        </action>
        
    </package>


    <!-- Add packages here -->

</struts>
复制代码

六、编写相关代码

注意事项:

dao继承HibernateDaoSupport类,所有数据库相关操作用hibernateTemplate操作;

给dao层,service层,action添加相应注解,注册为spring的bean;

附代码如下:

UserAction.java

 View Code

 AopTest.java

 View Code

MyAop.java

 View Code

BaseDao.java

 View Code

UserDao.java

 View Code

User.java

 View Code

User.hbm.xml

 View Code

UserService.java

 View Code

index.jsp(记得添加jquery库)

 View Code

七、验证结果

回到开头,开始熟悉了解相关技术,并验证结果

1、搭建传统的ssh开发环境,并成功运行(插入、查询)

如下图:查询及添加用户成功;

2、了解c3p0连接池相关配置

数据库连接是一种昂贵的资源,开启及关闭比较消耗性能,因此可以用连接池来管理,初始化若干个连接,重复使用,而不是重复创建关闭,有点类似线程池;

配置如下,要根据实际项目情况合理配置最小最大连接数,详细的各个参数含义可以参考链接

另外要验证连接数相关配置很简单,可以自己写个程序验证,比如当配置最大连接数为10的时候,可以写个程序验证,当打开10个connection后,第11个connection会一直处于等待状态,获取不到;所以要根据情况合理配置连接数,否则有可能会影响应用性能;

复制代码
    <!--配数据源 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo" />
        <property name="user" value="root" />
        <property name="password" value="root" />
        
            <property name="acquireIncrement" value="1"></property>  
            <property name="initialPoolSize" value="80"></property>  
            <property name="maxIdleTime" value="60"></property>  
            <property name="maxPoolSize" value="80"></property>  
            <property name="minPoolSize" value="30"></property>  
            <property name="acquireRetryDelay" value="1000"></property>  
            <property name="acquireRetryAttempts" value="60"></property>  
            <property name="breakAfterAcquireFailure" value="false"></property>
            <!-- 如出现Too many connections, 注意修改mysql的配置文件my.ini,增大最多连接数配置项,(查看当前连接命令:show processlist) -->
    </bean>
复制代码

3、了解验证hibernate的二级缓存,并验证

hibernate的一级缓存是指session范围的缓存,默认开启,二级缓存是sessionFactory范围缓存,在配置sessionFactory的时候,我们已经配置二级缓存为ehcache,接下来验证效果,查询user操作,发现第一次查询会操作数据库,打印sql语句,刷新页面后,发现查询成功且没打印sql语句,如下图,可见二级缓存工作OK;

4、了解spring事物配置,并验证

所谓事务控制,原理都一样,就是要保证原子性、一致性、隔离性、持久性,jdbc编程的时候,都是自己控制,通过set autocommit=false设置成不自动提交,然后开始写具体的数据库操作,发生异常的时候rollback,否则commit;其实spring对事物的控制原理也差不多,加了一些封装,配置等,更加方便而已,比如可以在service层不同方法进行控制等;

验证的话很简单,在service层某个方法(注意方法名要符合spring配置文件中配置的规则)内写两个插入user的操作,在中间抛出一个异常,然后执行,如果发现第一个user插入成功,说明事务控制失效,否则ok;

5、了解spring的IOC(依赖注入),将struts2的action对象(bean)交给spring管理,自定义bean等...并验证

仔细观察的话,在配置applicationContext.xml文件的过程中,主要工作都是在配置bean相关信息,这些bean都是事先创建好的,其实所谓的bean就是对象;

之所以把对象的创建交给spring容器,目的是为了解耦;

另外在用struts的时候,spring把action注册为bean,默认是单例的,访问的时候并不是每次都new出一个action,在并发访问的时候,会有风险;

不过,可以通过scope="prototype",把action配置成多例;ps:struts2中的action默认是多例;

注意:applicationContext.xml配置的bean和自定义注解的bean都是可以在程序运行的过程中直接获取的,通过@Resource等方式,这个很好验证,写个小程序即可;

6、了解spring aop(面向切面编程),并编写自定义切面函数,验证结果

切面编程这种形式很多地方都用了该思想,什么过滤器,拦截器,事务控制等等...

其原理还是java的反射和动态代理,在方法执行前后加以控制,加入自己要执行的代码;

小例子中加了个切面,在方法执行前后打印before和after字符串,如下图,工作正常,代码参考前面部分:

复制代码
   <!-- 自定义aop处理 测试 -->
   <bean id="aopTest" class="ssh.aop.AopTest"></bean>
   <bean id="myAop" class="ssh.aop.MyAop"></bean>
   <aop:config proxy-target-class="true">
        <aop:aspect ref="myAop">
            <aop:pointcut id="pcMethodTest" expression="execution(* ssh.aop.AopTest.test*(..))"/>
            <aop:before pointcut-ref="pcMethodTest" method="before"/>
            <aop:after pointcut-ref="pcMethodTest" method="after"/>
        </aop:aspect>
    </aop:config>
复制代码

 

本文转自风一样的码农博客园博客,原文链接:http://www.cnblogs.com/chenpi/p/5153593.html,如需转载请自行联系原作者

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
Spring boot + Mybatis + Thymeleaf + Druid +mySql
Spring boot + Mybatis + Thymeleaf + Druid +mySql
47 0
springboot2.4 整合mybatis-plus、mysql
springboot2.4 整合mybatis-plus、mysql
113 0
springboot学习-使用spring-data-jpa操作MySQL数据库
springboot学习-使用spring-data-jpa操作MySQL数据库
231 0
Spring Boot + MyBatis + MySQL读写分离
Spring Boot + MyBatis + MySQL读写分离
769 0
Spring Boot 2.x基础教程:使用MyBatis访问MySQL
Spring Boot 2.x基础教程:使用MyBatis访问MySQL
104 0
springboot整合mybatis、mysql、freemaker基础实现
springboot整合mybatis、mysql、freemaker基础实现
103 0
Spring Boot 2.x基础教程:使用Spring Data JPA访问MySQL
Spring Boot 2.x基础教程:使用Spring Data JPA访问MySQL
97 0
当Spring Boot遇见Mybatis(连接Mysql)
前言 在本文中讲述了Spring Boot 如何整合Mybatis ,然后如何通过Mybaits连接到Mysql,项目是由gradle构建的,本文还讲述了controller层相关的知识。
1833 0
Spring Boot入门(7)使用MyBatis操作MySQL
介绍 MyBatis 是一款优秀的、开源的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
1914 0
SpringBoot+Mybatis+MySql学习
介绍一下SpringBoot整合mybatis,数据库选用的是mysql。 首先创建数据库 CREATE DATABASE test; 建表以及插入初始数据(sql是从navicat中导出的) SET NAMES utf8mb4; SET FOREI...
1163 0
+关注
文艺小青年
文章
问答
视频
文章排行榜
最热
最新
相关电子书
更多
陈曦:使用Spring.Initializr定制工程脚手架
立即下载
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
相关实验场景
更多