准备

导包

Struts2

导入 Struts2 zip 包解压目录下 'apps/struts-blank.war' 中所有 jar 包,如下:

  1. asm-3.3.jar
  2. asm-commons-3.3.jar
  3. asm-tree-3.3.jar
  4. commons-fileupload-1.4.jar
  5. commons-io-2.2.jar
  6. commons-lang3-3.2.jar
  7. freemarker-2.3.28.jar
  8. javassist-3.11.0.GA.jar
  9. log4j-api-2.3.jar # 可选
  10. log4j-core-2.3.jar # 可选
  11. ognl-3.0.21.jar
  12. struts2-core-2.3.37.jar
  13. xwork-core-2.3.37.jar

另外导入 lib 下如下包:

  1. struts2-convention-plugin-2.3.37.jar # Struts2 注解开发包
  2. struts2-json-plugin-2.3.37.jar # Struts2 内置 Json 序列化支持包
  3. struts2-spring-plugin-2.3.37.jar # Struts2 整合 Spring 包

Hibernate

首先是 Hibernate 开发的必须包,即 Hibernate zip 包 解压目录下 'lib/required' 下所有的包,如下:

  1. antlr-2.7.7.jar
  2. dom4j-1.6.1.jar
  3. geronimo-jta_1.1_spec-1.1.1.jar
  4. hibernate-commons-annotations-5.0.1.Final.jar
  5. hibernate-core-5.0.7.Final.jar
  6. hibernate-jpa-2.1-api-1.0.0.Final.jar
  7. jandex-2.0.0.Final.jar
  8. javassist-3.18.1-GA.jar
  9. jboss-logging-3.3.0.Final.jar

Strut2 和 Hibernate 都引入了一个相同的 jar 包 javassisit,整合时必须只保留一个。

还需导入日志记录包

  1. log4j-1.2.16.jar
  2. slf4j-api-1.6.1.jar
  3. slf4j-log4j12-1.7.2.jar

如果使用这里的日志记录包,那么 Struts2 包中两个可选日志记录包就不需要引入。

如果 Hibernate 要使用 C3P0 连接池,还需引入 'lib\optional\c3p0' 下所有包,如下:

  1. c3p0-0.9.2.1.jar
  2. hibernate-c3p0-5.0.7.Final.jar
  3. mchange-commons-java-0.2.3.4.jar

当然,使用 Hibernate 还需要数据库驱动包,这里我使用 MySQL 驱动包

  1. mysql-connector-java-5.1.7-bin.jar

Spring

使用 IoC 需引入的包:

  1. com.springsource.org.apache.commons.logging-1.1.1.jar
  2. com.springsource.org.apache.log4j-1.2.15.jar
  3. spring-beans-4.2.4.RELEASE.jar
  4. spring-context-4.2.4.RELEASE.jar
  5. spring-core-4.2.4.RELEASE.jar
  6. spring-expression-4.2.4.RELEASE.jar

使用 AOP 需引入的包:

  1. com.springsource.org.aopalliance-1.0.0.jar
  2. com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
  3. spring-aop-4.2.4.RELEASE.jar
  4. spring-aspects-4.2.4.RELEASE.jar

使用 JDBC 模板需引入的包:

  1. spring-jdbc-4.2.4.RELEASE.jar
  2. spring-tx-4.2.4.RELEASE.jar

使用事务管理需引入的包:

  1. spring-tx-4.2.4.RELEASE.jar

整合 web 项目需引入的包:

  1. spring-web-4.2.4.RELEASE.jar

整合单元测试测试需引入的包:

  1. spring-test-4.2.4.RELEASE.jar

整合 ORM 框架 Hibernate 需引入的包:

  1. spring-orm-4.2.4.RELEASE.jar

上述完整 jar 包下载

配置

Struts2

配置 Struts2 的核心过滤器:

  1. <filter>
  2. <filter-name>struts2</filter-name>
  3. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>struts2</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>

WEB-INF/web.xml

引入 Struts2 核心配置文件:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  4. "http://struts.apache.org/dtds/struts-2.3.dtd">
  5. <struts>
  6. <package name="test" extends="struts-default" namespace="/">
  7.  
  8. </package>
  9. </struts>

struts.xml

Hibernate

引入核心配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <!-- 连接数据库的基本参数 -->
  8. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  9. <property name="hibernate.connection.url">jdbc:mysql:///test</property>
  10. <property name="hibernate.connection.username">root</property>
  11. <property name="hibernate.connection.password">root</property>
  12. <!-- 配置Hibernate的方言 -->
  13. <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  14. <!-- 可选配置================ -->
  15.  
  16. <!-- 打印SQL -->
  17. <property name="hibernate.show_sql">true</property>
  18. <!-- 格式化SQL -->
  19. <property name="hibernate.format_sql">true</property>
  20. <!-- 自动创建表 -->
  21. <property name="hibernate.hbm2ddl.auto">update</property>
  22. <!-- 配置C3P0连接池 -->
  23. <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
  24. <!--在连接池中可用的数据库连接的最少数目 -->
  25. <property name="c3p0.min_size">5</property>
  26. <!--在连接池中所有数据库连接的最大数目 -->
  27. <property name="c3p0.max_size">20</property>
  28. <!--设定数据库连接的过期时间,以秒为单位,
  29. 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
  30. <property name="c3p0.timeout">120</property>
  31. <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
  32. <property name="c3p0.idle_test_period">3000</property>
  33. </session-factory>
  34. </hibernate-configuration>

hibernate.cfg.xml

Spring

配置 Spring 的核心监听器:

  1. <listener>
  2. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  3. </listener>
  4. <!--默认情况下 Spring 会查找路径为 WEB-INF/applicationContext.xml 的配置文件,通过如下配置,让 Spring 在 classpath 下查找-->
  5. <context-param>
  6. <param-name>contextConfigLocation</param-name>
  7. <param-value>classpath:applicationContext.xml</param-value>
  8. </context-param>

WEB-INF/web.xml

引入核心配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15.  
  16. <!-- Spring整合Hibernate -->
  17. <!-- 引入Hibernate的配置的信息=============== -->
  18. <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  19. <!-- 引入hibernate的配置文件 -->
  20. <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
  21. </bean>
  22.  
  23. <!-- 配置事务管理器 -->
  24. <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  25. <property name="sessionFactory" ref="sessionFactory"/>
  26. </bean>
  27.  
  28. <!-- 开启注解事务 -->
  29. <tx:annotation-driven transaction-manager="transactionManager"/>
  30. </beans>

applicationContext.xml

Log4j 配置:

  1. ### direct log messages to stdout ###
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  3. log4j.appender.stdout.Target=System.err
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  6.  
  7. ### direct messages to file mylog.log ###
  8. log4j.appender.file=org.apache.log4j.FileAppender
  9. log4j.appender.file.File=c\:mylog.log
  10. log4j.appender.file.layout=org.apache.log4j.PatternLayout
  11. log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  12.  
  13. ### set log levels - for more verbose logging change 'info' to 'debug' ###
  14. # error warn info debug trace
  15. log4j.rootLogger= info, stdout

log4j.properties

代码

  1. package com.zze.domain;
  2.  
  3. public class User {
  4. private Integer id;
  5. private String name;
  6. private Integer age;
  7.  
  8. public Integer getId() {
  9. return id;
  10. }
  11.  
  12. public void setId(Integer id) {
  13. this.id = id;
  14. }
  15.  
  16. public String getName() {
  17. return name;
  18. }
  19.  
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23.  
  24. public Integer getAge() {
  25. return age;
  26. }
  27.  
  28. public void setAge(Integer age) {
  29. this.age = age;
  30. }
  31.  
  32. @Override
  33. public String toString() {
  34. return "User{" +
  35. "id=" + id +
  36. ", name='" + name + '\'' +
  37. '}';
  38. }
  39. }

com.zze.domain.User

  1. package com.zze.dao;
  2.  
  3. import com.zze.domain.User;
  4.  
  5. public interface UserDao {
  6. void save(User user);
  7. }

com.zze.dao.UserDao

  1. package com.zze.dao.impl;
  2.  
  3. import com.zze.dao.UserDao;
  4. import com.zze.domain.User;
  5.  
  6. public class UserDaoImpl implements UserDao {
  7. @Override
  8. public void save(User user) {
  9. }
  10. }

com.zze.dao.impl.UserDaoImpl

  1. package com.zze.service;
  2.  
  3. import com.zze.domain.User;
  4.  
  5. public interface UserService {
  6. void save(User user);
  7. }

com.zze.service.UserService

  1. package com.zze.service.impl;
  2.  
  3. import com.zze.dao.UserDao;
  4. import com.zze.domain.User;
  5. import com.zze.service.UserService;
  6.  
  7. public class UserServiceImpl implements UserService {
  8. private UserDao userDao;
  9.  
  10. public void setUserDao(UserDao userDao) {
  11. this.userDao = userDao;
  12. }
  13.  
  14. @Override
  15. public void save(User user) {
  16. userDao.save(user);
  17. }
  18. }

com.zze.service.impl.UserServiceImpl

  1. package com.zze.web.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.opensymphony.xwork2.ModelDriven;
  5. import com.zze.domain.User;
  6. public class UserAction extends ActionSupport implements ModelDriven<User> {
  7. private User user = new User();
  8.  
  9. @Override
  10. public User getModel() {
  11. return user;
  12. }
  13. }

com.zze.web.action.UserAction

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15.  
  16. <bean name="userService" class="com.zze.service.impl.UserServiceImpl">
  17. <property name="userDao" ref="userDao"/>
  18. </bean>
  19.  
  20. <bean name="userDao" class="com.zze.dao.impl.UserDaoImpl">
  21. </bean>
  22. </beans>

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  4. "http://struts.apache.org/dtds/struts-2.3.dtd">
  5. <struts>
  6. <package name="test" extends="struts-default" namespace="/">
  7. <action name="customer_*" class="com.zze.web.action.UserAction" method="{1}">
  8. </action>
  9. </package>
  10. </struts>

struts.xml

Spring整合Struts2

方式一:Action由Struts2自身创建

在 Action 中我们会调用业务层代码,如果按照传统方式,我们要获取到业务类实例,需要通过 Spring 工厂来手动获取,如下:

  1. package com.zze.web.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.opensymphony.xwork2.ModelDriven;
  5. import com.zze.domain.User;
  6. import com.zze.service.UserService;
  7. import org.apache.struts2.ServletActionContext;
  8. import org.springframework.web.context.WebApplicationContext;
  9. import org.springframework.web.context.support.WebApplicationContextUtils;
  10.  
  11. public class UserAction extends ActionSupport implements ModelDriven<User> {
  12. private User user = new User();
  13.  
  14. @Override
  15. public User getModel() {
  16. return user;
  17. }
  18.  
  19. public String save() {
  20. //传统方式获取 Service
  21. WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
  22. UserService userService = (UserService) applicationContext.getBean("userService");
  23. System.out.println(userService);
  24. /*
  25. 访问 http://localhost:8080/customer_save,输出结果如下:
  26. com.zze.service.impl.UserServiceImpl@4b65044b
  27. */
  28. return NONE;
  29. }
  30. }

com.zze.web.action.UserAction

而这种方式的代码显然过于复杂,Struts2 在与 Spring 整合时 Struts2 还为我们提供了更简易的方式哦。

Spring 整合 Struts2 需要引入一个 jar 包 struts2-spring-plugin.jar,这个 jar 包在上述准备工作中就已经引入,查看该 jar 中的 struts-plugin.xml:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!--
  3. /*
  4. * $Id$
  5. *
  6. * Licensed to the Apache Software Foundation (ASF) under one
  7. * or more contributor license agreements. See the NOTICE file
  8. * distributed with this work for additional information
  9. * regarding copyright ownership. The ASF licenses this file
  10. * to you under the Apache License, Version 2.0 (the
  11. * "License"); you may not use this file except in compliance
  12. * with the License. You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing,
  17. * software distributed under the License is distributed on an
  18. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19. * KIND, either express or implied. See the License for the
  20. * specific language governing permissions and limitations
  21. * under the License.
  22. */
  23. -->
  24. <!DOCTYPE struts PUBLIC
  25. "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  26. "http://struts.apache.org/dtds/struts-2.3.dtd">
  27.  
  28. <struts>
  29. <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
  30.  
  31. <!-- Make the Spring object factory the automatic default -->
  32. <constant name="struts.objectFactory" value="spring" />
  33.  
  34. <constant name="struts.class.reloading.watchList" value="" />
  35. <constant name="struts.class.reloading.acceptClasses" value="" />
  36. <constant name="struts.class.reloading.reloadConfig" value="false" />
  37. <constant name="xwork.disallowProxyMemberAccess" value="true" />
  38.  
  39. <package name="spring-default">
  40. <interceptors>
  41. <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
  42. </interceptors>
  43. </package>
  44. </struts>

struts2-spring-plugin-2.3.37.jar!/struts-plugin.xml

可以看到在该文件中配置了如下常量:

  1. <constant name="struts.objectFactory" value="spring" />

查看 Struts2 的默认配置:

  1. #
  2. # $Id$
  3. #
  4. # Licensed to the Apache Software Foundation (ASF) under one
  5. # or more contributor license agreements. See the NOTICE file
  6. # distributed with this work for additional information
  7. # regarding copyright ownership. The ASF licenses this file
  8. # to you under the Apache License, Version 2.0 (the
  9. # "License"); you may not use this file except in compliance
  10. # with the License. You may obtain a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing,
  15. # software distributed under the License is distributed on an
  16. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17. # KIND, either express or implied. See the License for the
  18. # specific language governing permissions and limitations
  19. # under the License.
  20. #
  21. ### START SNIPPET: complete_file
  22.  
  23. ### Struts default properties
  24. ###(can be overridden by a struts.properties file in the root of the classpath)
  25. ###
  26.  
  27. ### This can be used to set your default locale and encoding scheme
  28. # struts.locale=en_US
  29. struts.i18n.encoding=UTF-8
  30.  
  31. ### if specified, the default object factory can be overridden here
  32. ### Note: short-hand notation is supported in some cases, such as "spring"
  33. ### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here
  34. # struts.objectFactory = spring
  35.  
  36. ### specifies the autoWiring logic when using the SpringObjectFactory.
  37. ### valid values are: name, type, auto, and constructor (name is the default)
  38. struts.objectFactory.spring.autoWire = name
  39.  
  40. ### indicates to the struts-spring integration if Class instances should be cached
  41. ### this should, until a future Spring release makes it possible, be left as true
  42. ### unless you know exactly what you are doing!
  43. ### valid values are: true, false (true is the default)
  44. struts.objectFactory.spring.useClassCache = true
  45.  
  46. ### ensures the autowire strategy is always respected.
  47. ### valid values are: true, false (false is the default)
  48. struts.objectFactory.spring.autoWire.alwaysRespect = false
  49.  
  50. ### By default SpringObjectFactory doesn't support AOP
  51. ### This flag was added just temporally to check if nothing is broken
  52. ### See https://issues.apache.org/jira/browse/WW-4110
  53. struts.objectFactory.spring.enableAopSupport = false
  54.  
  55. ### if specified, the default object type determiner can be overridden here
  56. ### Note: short-hand notation is supported in some cases, such as "tiger" or "notiger"
  57. ### Alternatively, you can provide a com.opensymphony.xwork2.util.ObjectTypeDeterminer implementation name here
  58. ### Note: By default, com.opensymphony.xwork2.util.DefaultObjectTypeDeterminer is used which handles type detection
  59. ### using generics. com.opensymphony.xwork2.util.GenericsObjectTypeDeterminer was deprecated since XWork 2, it's
  60. ### functions are integrated in DefaultObjectTypeDeterminer now.
  61. ### To disable tiger support use the "notiger" property value here.
  62. #struts.objectTypeDeterminer = tiger
  63. #struts.objectTypeDeterminer = notiger
  64.  
  65. ### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data
  66. # struts.multipart.parser=cos
  67. # struts.multipart.parser=pell
  68. # struts.multipart.parser=jakarta-stream
  69. struts.multipart.parser=jakarta
  70. # uses javax.servlet.context.tempdir by default
  71. struts.multipart.saveDir=
  72. struts.multipart.maxSize=2097152
  73.  
  74. ### Load custom property files (does not override struts.properties!)
  75. # struts.custom.properties=application,org/apache/struts2/extension/custom
  76.  
  77. ### How request URLs are mapped to and from actions
  78. #struts.mapper.class=org.apache.struts2.dispatcher.mapper.DefaultActionMapper
  79.  
  80. ### Used by the DefaultActionMapper
  81. ### You may provide a comma separated list, e.g. struts.action.extension=action,jnlp,do
  82. ### The blank extension allows you to match directory listings as well as pure action names
  83. ### without interfering with static resources, which can be specified as an empty string
  84. ### prior to a comma e.g. struts.action.extension=, or struts.action.extension=x,y,z,,
  85. struts.action.extension=action,,
  86.  
  87. ### Used by FilterDispatcher
  88. ### If true then Struts serves static content from inside its jar.
  89. ### If false then the static content must be available at <context_path>/struts
  90. struts.serve.static=true
  91.  
  92. ### Used by FilterDispatcher
  93. ### This is good for development where one wants changes to the static content be
  94. ### fetch on each request.
  95. ### NOTE: This will only have effect if struts.serve.static=true
  96. ### If true -> Struts will write out header for static contents such that they will
  97. ### be cached by web browsers (using Date, Cache-Content, Pragma, Expires)
  98. ### headers).
  99. ### If false -> Struts will write out header for static contents such that they are
  100. ### NOT to be cached by web browser (using Cache-Content, Pragma, Expires
  101. ### headers)
  102. struts.serve.static.browserCache=true
  103.  
  104. ### Set this to false if you wish to disable implicit dynamic method invocation
  105. ### via the URL request. This includes URLs like foo!bar.action, as well as params
  106. ### like method:bar (but not action:foo).
  107. ### An alternative to implicit dynamic method invocation is to use wildcard
  108. ### mappings, such as <action name="*/*" method="{2}" class="actions.{1}">
  109. struts.enable.DynamicMethodInvocation = false
  110.  
  111. ### Set this to true if you wish to allow slashes in your action names. If false,
  112. ### Actions names cannot have slashes, and will be accessible via any directory
  113. ### prefix. This is the traditional behavior expected of WebWork applications.
  114. ### Setting to true is useful when you want to use wildcards and store values
  115. ### in the URL, to be extracted by wildcard patterns, such as
  116. ### <action name="*/*" method="{2}" class="actions.{1}"> to match "/foo/edit" or
  117. ### "/foo/save".
  118. struts.enable.SlashesInActionNames = false
  119.  
  120. ### Disables support for action: prefix
  121. struts.mapper.action.prefix.enabled = false
  122.  
  123. ### Blocks access to actions in other namespace than current with action: prefix
  124. struts.mapper.action.prefix.crossNamespaces = false
  125.  
  126. ### use alternative syntax that requires %{} in most places
  127. ### to evaluate expressions for String attributes for tags
  128. struts.tag.altSyntax=true
  129.  
  130. ### when set to true, Struts will act much more friendly for developers. This
  131. ### includes:
  132. ### - struts.i18n.reload = true
  133. ### - struts.configuration.xml.reload = true
  134. ### - raising various debug or ignorable problems to errors
  135. ### For example: normally a request to foo.action?someUnknownField=true should
  136. ### be ignored (given that any value can come from the web and it
  137. ### should not be trusted). However, during development, it may be
  138. ### useful to know when these errors are happening and be told of
  139. ### them right away.
  140. struts.devMode = false
  141.  
  142. ### when set to true, resource bundles will be reloaded on _every_ request.
  143. ### this is good during development, but should never be used in production
  144. ### struts.i18n.reload=false
  145.  
  146. ### Standard UI theme
  147. ### Change this to reflect which path should be used for JSP control tag templates by default
  148. struts.ui.theme=xhtml
  149. struts.ui.templateDir=template
  150. ### Change this to use a different token to indicate template theme expansion
  151. struts.ui.theme.expansion.token=~~~
  152. #sets the default template type. Either ftl, vm, or jsp
  153. struts.ui.templateSuffix=ftl
  154.  
  155. ### Configuration reloading
  156. ### This will cause the configuration to reload struts.xml when it is changed
  157. ### struts.configuration.xml.reload=false
  158.  
  159. ### Location of velocity.properties file. defaults to velocity.properties
  160. struts.velocity.configfile = velocity.properties
  161.  
  162. ### Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContext
  163. struts.velocity.contexts =
  164.  
  165. ### Location of the velocity toolbox
  166. struts.velocity.toolboxlocation=
  167.  
  168. ### used to build URLs, such as the UrlTag
  169. struts.url.http.port = 80
  170. struts.url.https.port = 443
  171. ### possible values are: none, get or all
  172. struts.url.includeParams = none
  173.  
  174. ### Load custom default resource bundles
  175. # struts.custom.i18n.resources=testmessages,testmessages2
  176.  
  177. ### workaround for some app servers that don't handle HttpServletRequest.getParameterMap()
  178. ### often used for WebLogic, Orion, and OC4J
  179. struts.dispatcher.parametersWorkaround = false
  180.  
  181. ### configure the Freemarker Manager class to be used
  182. ### Allows user to plug-in customised Freemarker Manager if necessary
  183. ### MUST extends off org.apache.struts2.views.freemarker.FreemarkerManager
  184. #struts.freemarker.manager.classname=org.apache.struts2.views.freemarker.FreemarkerManager
  185.  
  186. ### Enables caching of FreeMarker templates
  187. ### Has the same effect as copying the templates under WEB_APP/templates
  188. ### struts.freemarker.templatesCache=false
  189.  
  190. ### Enables caching of models on the BeanWrapper
  191. struts.freemarker.beanwrapperCache=false
  192.  
  193. ### See the StrutsBeanWrapper javadocs for more information
  194. struts.freemarker.wrapper.altMap=true
  195.  
  196. ### maxStrongSize for MruCacheStorage for freemarker, when set to 0 SoftCacheStorage which performs better in heavy loaded application
  197. ### check WW-3766 for more details
  198. struts.freemarker.mru.max.strong.size=0
  199.  
  200. ### configure the XSLTResult class to use stylesheet caching.
  201. ### Set to true for developers and false for production.
  202. struts.xslt.nocache=false
  203.  
  204. ### Whether to always select the namespace to be everything before the last slash or not
  205. struts.mapper.alwaysSelectFullNamespace=false
  206.  
  207. ### Whether to allow static method access in OGNL expressions or not
  208. struts.ognl.allowStaticMethodAccess=false
  209.  
  210. ### Whether to throw a RuntimeException when a property is not found
  211. ### in an expression, or when the expression evaluation fails
  212. struts.el.throwExceptionOnFailure=false
  213.  
  214. ### Logs as Warnings properties that are not found (very verbose)
  215. struts.ognl.logMissingProperties=false
  216.  
  217. ### Caches parsed OGNL expressions, but can lead to memory leaks
  218. ### if the application generates a lot of different expressions
  219. struts.ognl.enableExpressionCache=true
  220.  
  221. ### Indicates if Dispatcher should handle unexpected exceptions by calling sendError()
  222. ### or simply rethrow it as a ServletException to allow future processing by other frameworks like Spring Security
  223. struts.handle.exception=true
  224. ### END SNIPPET: complete_file

struts2-core-2.3.37.jar!/org/apache/struts2/default.properties

在第 34 行可以看到,该常量默认是关闭的,而该常量只要开启,第 38 行的常量就会生效:

  1. ### specifies the autoWiring logic when using the SpringObjectFactory.
  2. ### valid values are: name, type, auto, and constructor (name is the default)
  3. struts.objectFactory.spring.autoWire = name

而该配置的作用就是让 Action 可以按照变量名称自动注入 Spring 工厂中管理的实例,所以业务类实例还可通过如下方式获取:

  1. package com.zze.web.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.opensymphony.xwork2.ModelDriven;
  5. import com.zze.domain.User;
  6. import com.zze.service.UserService;
  7.  
  8. public class UserAction extends ActionSupport implements ModelDriven<User> {
  9. private User user = new User();
  10.  
  11. @Override
  12. public User getModel() {
  13. return user;
  14. }
  15.  
  16. private UserService userService;
  17.  
  18. public void setUserService(UserService userService) {
  19. this.userService = userService;
  20. }
  21.  
  22. public String save() {
  23. System.out.println(userService);
  24. /*
  25. 访问 http://localhost:8080/customer_save,输出结果如下:
  26. com.zze.service.impl.UserServiceImpl@389b9f55
  27. */
  28. return NONE;
  29. }
  30. }

com.zze.web.action.UserAction

方式二:Action由Spring创建

修改配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15.  
  16. <!--
  17. 让 Spring 来创建 Action 实例
  18. 注意,Action 类要配置为多例
  19. -->
  20. <bean name="userAction" class="com.zze.web.action.UserAction" scope="prototype">
  21. <property name="userService" ref="userService"/>
  22. </bean>
  23.  
  24. <bean name="userService" class="com.zze.service.impl.UserServiceImpl">
  25. <property name="userDao" ref="userDao"/>
  26. </bean>
  27.  
  28. <bean name="userDao" class="com.zze.dao.impl.UserDaoImpl">
  29. </bean>
  30. </beans>

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  4. "http://struts.apache.org/dtds/struts-2.3.dtd">
  5. <struts>
  6. <package name="test" extends="struts-default" namespace="/">
  7. <!--
  8. 修改 class 对应 applicationContext.xml 中 bean 的名称 (id/name)
  9. -->
  10. <action name="customer_*" class="userAction" method="{1}">
  11. </action>
  12. </package>
  13. </struts>

struts.xml

测试:

  1. package com.zze.web.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.opensymphony.xwork2.ModelDriven;
  5. import com.zze.domain.User;
  6. import com.zze.service.UserService;
  7.  
  8. public class UserAction extends ActionSupport implements ModelDriven<User> {
  9. private User user = new User();
  10.  
  11. @Override
  12. public User getModel() {
  13. return user;
  14. }
  15.  
  16. private UserService userService;
  17.  
  18. public void setUserService(UserService userService) {
  19. this.userService = userService;
  20. }
  21.  
  22. public String save() {
  23. System.out.println(userService);
  24. /*
  25. 访问 http://localhost:8080/customer_save,输出结果如下:
  26. com.zze.service.impl.UserServiceImpl@4f543a20
  27. */
  28. return NONE;
  29. }
  30. }

com.zze.web.action.UserAction

Spring整合Hibernate

方式一:保留Hibernate配置文件

编写实体映射文件:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  5.  
  6. <hibernate-mapping>
  7. <class name="com.zze.domain.User" table="user">
  8. <id name="id" column="id">
  9. <generator class="native"/>
  10. </id>
  11. <property name="name" column="name" length="32"/>
  12. <property name="age" column="age"/>
  13. </class>
  14. </hibernate-mapping>

com/zze/domain/User.hbm.xml

在 Hibernate 核心配置文件中引入实体映射文件:

  1. <mapping resource="com/zze/domain/User.hbm.xml"/>

hibernate.cfg.xml

修改 Dao 代码:

  1. package com.zze.dao.impl;
  2.  
  3. import com.zze.dao.UserDao;
  4. import com.zze.domain.User;
  5. import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
  6. // 使用 Hibernate 提供的 Dao 模板类
  7. public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
  8.  
  9. @Override
  10. public void save(User user) {
  11. this.getHibernateTemplate().save(user);
  12. }
  13. }

com.zze.dao.impl.UserDaoImpl

将 Hibernate 的核心工厂类实例交给 Spring 创建:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15. <!--Spring 整合 Hibernate-->
  16. <!--引入 Hibernate 配置信息-->
  17. <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  18. <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
  19. </bean>
  20. <!--
  21. <bean name="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
  22. <property name="sessionFactory" ref="sessionFactory"/>
  23. </bean>
  24. -->
  25.  
  26. <!-- 配置事务管理器 -->
  27. <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  28. <property name="sessionFactory" ref="sessionFactory"/>
  29. </bean>
  30.  
  31. <!-- 开启注解事务 -->
  32. <tx:annotation-driven transaction-manager="transactionManager"/>
  33.  
  34. <!--Spring 整合 Struts2-->
  35. <!--
  36. 让 Spring 来创建 Action 实例
  37. 注意,Action 类要配置为多例
  38. -->
  39. <bean name="userAction" class="com.zze.web.action.UserAction" scope="prototype">
  40. <property name="userService" ref="userService"/>
  41. </bean>
  42.  
  43. <bean name="userService" class="com.zze.service.impl.UserServiceImpl">
  44. <property name="userDao" ref="userDao"/>
  45. </bean>
  46.  
  47. <bean name="userDao" class="com.zze.dao.impl.UserDaoImpl">
  48. <property name="sessionFactory" ref="sessionFactory"/>
  49. <!--
  50. <property name="hibernateTemplate" ref="hibernateTemplate"/>
  51. -->
  52. </bean>
  53. </beans>

applicationContext.xml

测试:

  1. package com.zze.web.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.opensymphony.xwork2.ModelDriven;
  5. import com.zze.domain.User;
  6. import com.zze.service.UserService;
  7.  
  8. public class UserAction extends ActionSupport implements ModelDriven<User> {
  9. private User user = new User();
  10.  
  11. @Override
  12. public User getModel() {
  13. return user;
  14. }
  15.  
  16. private UserService userService;
  17.  
  18. public void setUserService(UserService userService) {
  19. this.userService = userService;
  20. }
  21.  
  22. public String save() {
  23. userService.save(user);
  24. return NONE;
  25. }
  26. }

com.zze.web.action.UserAction

方式二:去除Hibernate配置文件

新建数据库连接信息属性文件:

  1. jdbc.driverClass=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql:///test
  3. jdbc.username=root
  4. jdbc.password=root

jdbc.properties

删除 Hibernate 配置文件 hibernate.cfg.xml,在 Spring 配置文件中完成 Hibernate 相关配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15. <context:property-placeholder location="classpath:jdbc.properties"/>
  16. <!--配置 C3P0 数据源-->
  17. <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  18. <property name="driverClass" value="${jdbc.driverClass}"/>
  19. <property name="jdbcUrl" value="${jdbc.url}"/>
  20. <property name="user" value="${jdbc.username}"/>
  21. <property name="password" value="${jdbc.password}"/>
  22. </bean>
  23. <!--Spring 整合 Hibernate-->
  24. <!--引入 Hibernate 配置信息-->
  25. <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  26. <!-- 注入连接池 -->
  27. <property name="dataSource" ref="dataSource"/>
  28. <!-- 配置Hibernate的相关属性 -->
  29. <property name="hibernateProperties">
  30. <props>
  31. <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
  32. <prop key="hibernate.show_sql">true</prop>
  33. <prop key="hibernate.format_sql">true</prop>
  34. <prop key="hibernate.hbm2ddl.auto">update</prop>
  35. </props>
  36. </property>
  37.  
  38. <!-- 设置映射文件 -->
  39. <property name="mappingResources">
  40. <list>
  41. <value>com/zze/domain/User.hbm.xml</value>
  42. </list>
  43. </property>
  44. </bean>
  45. <!--
  46. <bean name="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
  47. <property name="sessionFactory" ref="sessionFactory"/>
  48. </bean>
  49. -->
  50.  
  51. <!-- 配置事务管理器 -->
  52. <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  53. <property name="sessionFactory" ref="sessionFactory"/>
  54. </bean>
  55.  
  56. <!-- 开启注解事务 -->
  57. <tx:annotation-driven transaction-manager="transactionManager"/>
  58.  
  59. <!--Spring 整合 Struts2-->
  60. <!--
  61. 让 Spring 来创建 Action 实例
  62. 注意,Action 类要配置为多例
  63. -->
  64. <bean name="userAction" class="com.zze.web.action.UserAction" scope="prototype">
  65. <property name="userService" ref="userService"/>
  66. </bean>
  67.  
  68. <bean name="userService" class="com.zze.service.impl.UserServiceImpl">
  69. <property name="userDao" ref="userDao"/>
  70. </bean>
  71.  
  72. <bean name="userDao" class="com.zze.dao.impl.UserDaoImpl">
  73. <property name="sessionFactory" ref="sessionFactory"/>
  74. <!--
  75. <property name="hibernateTemplate" ref="hibernateTemplate"/>
  76. -->
  77. </bean>
  78. </beans>

applicationContext.xml

测试:

  1. package com.zze.web.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.opensymphony.xwork2.ModelDriven;
  5. import com.zze.domain.User;
  6. import com.zze.service.UserService;
  7.  
  8. public class UserAction extends ActionSupport implements ModelDriven<User> {
  9. private User user = new User();
  10.  
  11. @Override
  12. public User getModel() {
  13. return user;
  14. }
  15.  
  16. private UserService userService;
  17.  
  18. public void setUserService(UserService userService) {
  19. this.userService = userService;
  20. }
  21.  
  22. public String save() {
  23. userService.save(user);
  24. return NONE;
  25. }
  26. }

com.zze.web.action.UserAction

补充

延迟加载问题

Hibernate 是有延迟加载策略的,Spring 整合 Hibernate 后,session 的是由 Spring 管理的。当我们做一个有延迟加载的查询操作时,默认情况下在 service 层已经完成了 session 的开启与关闭操作,所以如果我们要在 web 层使用延迟加载,此时 session 是关闭的状态,会抛出如下异常:

对于这个问题 Spring 也给我们提供了解决方案,只需要配置上它提供的一个过滤器即可,如下:

  1. <filter>
  2. <filter-name>openSessionInViewFilter</filter-name>
  3. <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>openSessionInViewFilter</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>

WEB-INF/web.xml

抽取通用Dao

  1. package com.zze.dao;
  2.  
  3. import org.hibernate.criterion.DetachedCriteria;
  4.  
  5. import java.io.Serializable;
  6. import java.util.List;
  7.  
  8. public interface BaseDao<T> {
  9. /**
  10. * 保存操作
  11. *
  12. * @param model 要保存的模型
  13. */
  14. void save(T model);
  15.  
  16. /**
  17. * 更新操作
  18. *
  19. * @param model 要更新的模型
  20. */
  21. void update(T model);
  22.  
  23. /**
  24. * 删除操作
  25. *
  26. * @param id 删除的 id
  27. */
  28. void delete(Serializable id);
  29.  
  30. /**
  31. * 通过 id 查询单个对象
  32. *
  33. * @param id 要删除数据主键
  34. * @return 返回 id 对应的单个对象
  35. */
  36. T findById(Serializable id);
  37.  
  38. /**
  39. * 查询所有数据
  40. *
  41. * @return 以 List 方式返回所有数据
  42. */
  43. List<T> findAll();
  44.  
  45. /**
  46. * 查询数据条数
  47. *
  48. * @param detachedCriteria 离线查询对象
  49. * @return 数据条数
  50. */
  51. Serializable findCount(DetachedCriteria detachedCriteria);
  52.  
  53. /**
  54. * 分页查询
  55. *
  56. * @param detachedCriteria 离线查询对象
  57. * @param begin 数据起始索引
  58. * @param pageSize 每页数据条数
  59. * @return 返回分页的珊瑚橘
  60. */
  61. List<T> findPage(DetachedCriteria detachedCriteria, Integer begin, Integer pageSize);
  62.  
  63. }

com.zze.dao.BaseDao

  1. package com.zze.dao.impl;
  2.  
  3. import com.zze.dao.BaseDao;
  4. import org.hibernate.criterion.DetachedCriteria;
  5. import org.hibernate.criterion.Projections;
  6. import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
  7.  
  8. import java.io.Serializable;
  9. import java.lang.reflect.ParameterizedType;
  10. import java.lang.reflect.Type;
  11. import java.util.List;
  12.  
  13. public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
  14.  
  15. private Class clazz;
  16.  
  17. public BaseDaoImpl() {
  18. /*
  19. 例: class UserDaoImpl extends BaseDaoImpl<User>
  20. */
  21. // 获取到运行时实际类 UserDaoImpl
  22. Class<? extends BaseDaoImpl> actualClass = this.getClass();
  23. // 获取到实际类父类 BaseDaoImpl<User>
  24. Type genericSuperclass = actualClass.getGenericSuperclass();
  25. // 转为参数化类型
  26. ParameterizedType type = (ParameterizedType) genericSuperclass;
  27. // 获取类型化参数 User
  28. Type[] actualTypeArguments = type.getActualTypeArguments();
  29. this.clazz = (Class) actualTypeArguments[0];
  30. }
  31.  
  32. @Override
  33. public void save(T model) {
  34. this.getHibernateTemplate().save(model);
  35. }
  36.  
  37. @Override
  38. public void update(T model) {
  39. this.getHibernateTemplate().update(model);
  40. }
  41.  
  42. @Override
  43. public void delete(Serializable id) {
  44. this.getHibernateTemplate().delete(id);
  45. }
  46.  
  47. @Override
  48. public T findById(Serializable id) {
  49. return (T) this.getHibernateTemplate().get(clazz, id);
  50. }
  51.  
  52. @Override
  53. public List<T> findAll() {
  54. return (List<T>) this.getHibernateTemplate().find("from " + clazz.getSimpleName());
  55. }
  56.  
  57. @Override
  58. public Serializable findCount(DetachedCriteria detachedCriteria) {
  59. detachedCriteria.setProjection(Projections.rowCount());
  60. List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
  61. return list.size() > 0 ? list.get(0).intValue() : null;
  62. }
  63.  
  64. @Override
  65. public List<T> findPage(DetachedCriteria detachedCriteria,Integer begin,Integer pageSize) {
  66. detachedCriteria.setProjection(null);
  67. return (List<T>) this.getHibernateTemplate().findByCriteria(detachedCriteria, begin, pageSize);
  68. }
  69. }

com.zze.dao.impl.BaseDaoImpl

SSH注解整合

1、导包,同上述准备工作中包。

2、配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <!--Struts2 过滤器-->
  7. <filter>
  8. <filter-name>struts2</filter-name>
  9. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  10. </filter>
  11. <filter-mapping>
  12. <filter-name>struts2</filter-name>
  13. <url-pattern>/*</url-pattern>
  14. </filter-mapping>
  15.  
  16. <!--Spring 核心监听器-->
  17. <listener>
  18. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  19. </listener>
  20.  
  21. <!--配置 Spring 配置文件加载路径,默认加载 WEB-INF/applicationContext.xml-->
  22. <context-param>
  23. <param-name>contextConfigLocation</param-name>
  24. <param-value>classpath:applicationContext.xml</param-value>
  25. </context-param>
  26. </web-app>

WEB-INF/web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15. <context:property-placeholder location="classpath:jdbc.properties"/>
  16. <!--开启组件扫描-->
  17. <context:component-scan base-package="com.zze"/>
  18. <!--配置 C3P0 数据源-->
  19. <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  20. <property name="driverClass" value="${jdbc.driverClass}"/>
  21. <property name="jdbcUrl" value="${jdbc.url}"/>
  22. <property name="user" value="${jdbc.username}"/>
  23. <property name="password" value="${jdbc.password}"/>
  24. </bean>
  25. <!--Spring 整合 Hibernate-->
  26. <!--引入 Hibernate 配置信息-->
  27. <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  28. <!-- 注入连接池 -->
  29. <property name="dataSource" ref="dataSource"/>
  30. <!-- 配置Hibernate的相关属性 -->
  31. <property name="hibernateProperties">
  32. <props>
  33. <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
  34. <prop key="hibernate.show_sql">true</prop>
  35. <prop key="hibernate.format_sql">true</prop>
  36. <prop key="hibernate.hbm2ddl.auto">update</prop>
  37. </props>
  38. </property>
  39. <!--配置映射扫描-->
  40. <property name="packagesToScan" value="com.zze.domain"/>
  41. </bean>
  42.  
  43. <!-- 配置事务管理器 -->
  44. <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  45. <property name="sessionFactory" ref="sessionFactory"/>
  46. </bean>
  47.  
  48. <!-- 开启注解事务 -->
  49. <tx:annotation-driven transaction-manager="transactionManager"/>
  50.  
  51. <bean name="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
  52. <property name="sessionFactory" ref="sessionFactory"/>
  53. </bean>
  54. </beans>

applicationContext.xml

  1. jdbc.driverClass=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql:///test
  3. jdbc.username=root
  4. jdbc.password=root

jdbc.properties

  1. ### direct log messages to stdout ###
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  3. log4j.appender.stdout.Target=System.err
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  6.  
  7. ### direct messages to file mylog.log ###
  8. log4j.appender.file=org.apache.log4j.FileAppender
  9. log4j.appender.file.File=c\:mylog.log
  10. log4j.appender.file.layout=org.apache.log4j.PatternLayout
  11. log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  12.  
  13. ### set log levels - for more verbose logging change 'info' to 'debug' ###
  14. # error warn info debug trace
  15. log4j.rootLogger= info, stdout

log4j.properties

3、使用注解:

  1. package com.zze.domain;
  2.  
  3. import javax.persistence.*;
  4.  
  5. @Table(name = "user")
  6. @Entity
  7. public class User {
  8. @Id
  9. @Column(name = "id")
  10. @GeneratedValue(strategy = GenerationType.IDENTITY)
  11. private Integer id;
  12. @Column(name = "name")
  13. private String name;
  14. @Column(name = "age")
  15. private Integer age;
  16.  
  17. public Integer getId() {
  18. return id;
  19. }
  20.  
  21. public void setId(Integer id) {
  22. this.id = id;
  23. }
  24.  
  25. public String getName() {
  26. return name;
  27. }
  28.  
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32.  
  33. public Integer getAge() {
  34. return age;
  35. }
  36.  
  37. public void setAge(Integer age) {
  38. this.age = age;
  39. }
  40.  
  41. @Override
  42. public String toString() {
  43. return "User{" +
  44. "id=" + id +
  45. ", name='" + name + '\'' +
  46. '}';
  47. }
  48. }

com.zze.domain.User : Hibernate 实体映射注解

  1. package com.zze.dao.impl;
  2.  
  3. import com.zze.dao.BaseDao;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.criterion.DetachedCriteria;
  6. import org.hibernate.criterion.Projections;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.orm.hibernate5.HibernateTemplate;
  9. import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
  10.  
  11. import javax.annotation.Resource;
  12. import java.io.Serializable;
  13. import java.lang.reflect.ParameterizedType;
  14. import java.lang.reflect.Type;
  15. import java.util.List;
  16.  
  17. public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
  18.  
  19. /**
  20. * 注入 sessionFactory
  21. *
  22. * @param sessionFactory
  23. */
  24. @Autowired
  25. private void setSF(SessionFactory sessionFactory) {
  26. super.setSessionFactory(sessionFactory);
  27. }
  28.  
  29. /*
  30. @Resource(name = "hibernateTemplate")
  31. private HibernateTemplate hibernateTemplate;
  32. */
  33. private Class clazz;
  34.  
  35. public BaseDaoImpl() {
  36. /*
  37. 例: class UserDaoImpl extends BaseDaoImpl<User>
  38. */
  39. // 获取到运行时实际类 UserDaoImpl
  40. Class<? extends BaseDaoImpl> actualClass = this.getClass();
  41. // 获取到实际类父类 BaseDaoImpl<User>
  42. Type genericSuperclass = actualClass.getGenericSuperclass();
  43. // 转为参数化类型
  44. ParameterizedType type = (ParameterizedType) genericSuperclass;
  45. // 获取类型化参数 User
  46. Type[] actualTypeArguments = type.getActualTypeArguments();
  47. this.clazz = (Class) actualTypeArguments[0];
  48. }
  49.  
  50. @Override
  51. public void save(T model) {
  52. this.getHibernateTemplate().save(model);
  53. }
  54.  
  55. @Override
  56. public void update(T model) {
  57. this.getHibernateTemplate().update(model);
  58. }
  59.  
  60. @Override
  61. public void delete(Serializable id) {
  62. this.getHibernateTemplate().delete(id);
  63. }
  64.  
  65. @Override
  66. public T findById(Serializable id) {
  67. return (T) this.getHibernateTemplate().get(clazz, id);
  68. }
  69.  
  70. @Override
  71. public List<T> findAll() {
  72. return (List<T>) this.getHibernateTemplate().find("from " + clazz.getSimpleName());
  73. }
  74.  
  75. @Override
  76. public Serializable findCount(DetachedCriteria detachedCriteria) {
  77. detachedCriteria.setProjection(Projections.rowCount());
  78. List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
  79. return list.size() > 0 ? list.get(0).intValue() : null;
  80. }
  81.  
  82. @Override
  83. public List<T> findPage(DetachedCriteria detachedCriteria, Integer begin, Integer pageSize) {
  84. detachedCriteria.setProjection(null);
  85. return (List<T>) this.getHibernateTemplate().findByCriteria(detachedCriteria, begin, pageSize);
  86. }
  87. }

com.zze.dao.impl.BaseDaoImpl : dao 层注入 sessionFactory

  1. package com.zze.dao.impl;
  2.  
  3. import com.zze.dao.UserDao;
  4. import com.zze.domain.User;
  5. import org.springframework.stereotype.Repository;
  6.  
  7. @Repository("userDao")
  8. public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {
  9.  
  10. }

com.zze.dao.impl.UserDaoImpl : dao 层实例化注解

  1. package com.zze.service.impl;
  2.  
  3. import com.zze.dao.UserDao;
  4. import com.zze.domain.User;
  5. import com.zze.service.UserService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Transactional;
  9.  
  10. @Transactional
  11. @Service("userService")
  12. public class UserServiceImpl implements UserService {
  13. @Autowired
  14. private UserDao userDao;
  15.  
  16. @Override
  17. public void save(User user) {
  18. userDao.save(user);
  19. }
  20. }

com.zze.service.impl.UserServiceImpl : service 层实例化和事务注解

  1. package com.zze.web.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.opensymphony.xwork2.ModelDriven;
  5. import com.zze.domain.User;
  6. import com.zze.service.UserService;
  7. import org.apache.struts2.convention.annotation.Action;
  8. import org.apache.struts2.convention.annotation.Namespace;
  9. import org.apache.struts2.convention.annotation.ParentPackage;
  10. import org.apache.struts2.convention.annotation.Result;
  11. import org.springframework.stereotype.Controller;
  12.  
  13. @Controller("userAction")
  14. @ParentPackage("struts-default")
  15. @Namespace("/user")
  16. public class UserAction extends ActionSupport implements ModelDriven<User> {
  17. private User user = new User();
  18.  
  19. @Override
  20. public User getModel() {
  21. return user;
  22. }
  23.  
  24. private UserService userService;
  25.  
  26. public void setUserService(UserService userService) {
  27. this.userService = userService;
  28. }
  29. // 访问路径 localhost:8080/user/save
  30. @Action(value = "save",results = {@Result(name = "success",location = "/index.jsp")})
  31. public String save() {
  32. userService.save(user);
  33. return NONE;
  34. }
  35. }

com.zze.web.action.UserAction : web 层实例化和 Struts2 配置注解

属性文件值注入

  1. jdbc.driverClass=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql:///test
  3. jdbc.username=root
  4. jdbc.password=root

jdbc.properties

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd">
  9. <context:property-placeholder location="classpath:jdbc.properties"/>
  10. </beans>

applicationContext.xml

  1. package com.zze.spring.test;
  2.  
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8.  
  9. @RunWith(SpringJUnit4ClassRunner.class)
  10. @ContextConfiguration("classpath:applicationContext.xml")
  11. public class Demo {
  12. @Value("${jdbc.driverClass}")
  13. private String driverClass;
  14. @Value("${jdbc.url}")
  15. private String url;
  16. @Value("${jdbc.username}")
  17. private String username;
  18. @Value("${jdbc.password}")
  19. private String password;
  20.  
  21. @Test
  22. public void test() {
  23. System.out.println(driverClass);
  24. System.out.println(url);
  25. System.out.println(username);
  26. System.out.println(password);
  27.  
  28. /*
  29. com.mysql.jdbc.Driver
  30. jdbc:mysql:///test
  31. root
  32. root
  33. */
  34. }
  35. }

com.zze.spring.test.Demo

java框架之Spring(4)-Spring整合Hibernate和Struts2的更多相关文章

  1. 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】

    一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...

  2. Spring Data初步--整合Hibernate

    Spring Data课程中的技术介绍 Hibernate: Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,它将 pojo 与数据库表建立映射关系 ...

  3. Spring学习7-Spring整合Hibernate

    一.Springl为什么要整合Hibernate   二者的整合主要是把hibernate中核心的一些类型交给spring管理,这些类型主要包括sessionFactory. transactionM ...

  4. java框架之Quartz-任务调度&整合Spring

    准备 介绍 定时任务,无论是互联网公司还是传统的软件行业都是必不可少的.Quartz,它是好多优秀的定时任务开源框架的基础,使用它,我们可以使用最简单基础的配置来轻松的使用定时任务. Quartz 是 ...

  5. java框架之MyBatis(2)-进阶&整合Spring&逆向工程

    进阶内容 准备 jdbc.url=jdbc:mysql://192.168.208.192:3306/test?characterEncoding=utf-8 jdbc.driver=com.mysq ...

  6. Spring再接触 整合Hibernate

    首先更改配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http ...

  7. java框架之SpringMVC(1)-入门&整合MyBatis

    前言 SpringMVC简介 SpringMVC 是一个类似于 Struts2 表现层的框架,属于 SpringFramework 的后续产品. 学习SpringMVC的原因 SpringMVC 与 ...

  8. 【java框架】SpringBoot(7) -- SpringBoot整合MyBatis

    1.整合MyBatis操作 前面一篇提到了SpringBoot整合基础的数据源JDBC.Druid操作,实际项目中更常用的还是MyBatis框架,而SpringBoot整合MyBatis进行CRUD也 ...

  9. 【java框架】SpringBoot(5)--SpringBoot整合分布式Dubbo+Zookeeper

    1.理论概述 1.1.分布式 分布式系统是若干独立计算机的集合,这些计算机对于用户来讲就像单个系统. 由多个系统集成成一个整体,提供多个功能,组合成一个板块,用户在使用上看起来是一个服务.(比如淘宝网 ...

随机推荐

  1. 获取CPU序列号的Delphi程序

    Unit CPUid; Interface Type TCpuType = (cpu8086, cpu286, cpu386, cpu486, cpuPentium); Function CpuTyp ...

  2. ES容易忽视的集群配置

    一 前言 目前生产系统由Solr转ES了,在这边就记录下在使用过程中容易忽视的配置吧,其实我也是才用,如果有什么错误的地方,多指正. 二.配置 1.ES的段合并是限速设置 默认是20MB/s ,如果是 ...

  3. win10 caffe python Faster-RCNN训练自己数据集(转)

    一.制作数据集 1. 关于训练的图片 不论你是网上找的图片或者你用别人的数据集,记住一点你的图片不能太小,width和height最好不要小于150.需要是jpeg的图片. 2.制作xml文件 1)L ...

  4. 框架源码系列五:学习源码的方法(学习源码的目的、 学习源码的方法、Eclipse里面查看源码的常用快捷键和方法)

    一. 学习源码的目的 1. 为了扩展和调优:掌握框架的工作流程和原理 2. 为了提升自己的编程技能:学习他人的设计思想.编程技巧 二. 学习源码的方法 方法一: 1)掌握研究的对象和研究对象的核心概念 ...

  5. laravel5.8笔记二:部署

    部署项目之前需要知道的几件事 1.有几个模块(admin,index,wap,api) 2.有几个数据库(mysql1,mysql2,mysql3) 3.有那些缓存(redis1,redis2,red ...

  6. visual studio 2019密钥

    企业版:BF8Y8-GN2QH-T84XB-QVY3B-RC4DF 专业版:NYWVH-HT4XC-R2WYW-9Y3CM-X4V3Y

  7. IntelliJ IDEA License Server 安装使用 Mac篇

    一.下载 IntelliJ IDEA 是Java开发利器,用社区版不爽,干催就用旗舰版,这个是收费的,需要licence.  IntelliJ IDEA下载地址:https://www.jetbrai ...

  8. phpstudy 升级(更换) mysql 版本

    原文链接:http://phpstudy.php.cn/jishu-php-3131.html 一.下载新版 mysql 例如 mysql5.7: https://dev.mysql.com/down ...

  9. 《Spring实战》学习笔记-第五章:构建Spring web应用

    之前一直在看<Spring实战>第三版,看到第五章时发现很多东西已经过时被废弃了,于是现在开始读<Spring实战>第四版了,章节安排与之前不同了,里面应用的应该是最新的技术. ...

  10. Spring data jpa JavassistLazyInitializer 不仅是Json序列化问题.以及解决办法

    最近偷点时间更新一下框架,使用SpringBoot2.0 整套一起更新一下,发现些小问题 Spring data jpa getOne 返回的是代理对象,延迟加载的,ResponseBody成Json ...