spring4 hibernate4 struts2 maven的整合

xmnx 10年前

代码并不规范,也没有service层,目的只是在于说明三大框架如何整合在一起,适合于个人练习。
直接上代码:
1 新建maven工程,pom.xml文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">      <modelVersion>4.0.0</modelVersion>        <groupId>com.abigdreamer.ark</groupId>      <artifactId>demo</artifactId>      <version>0.0.1-SNAPSHOT</version>      <packaging>war</packaging>        <name>data-permission</name>      <url>http://maven.apache.org</url>      <properties>          <org.hibernate.version>4.1.2</org.hibernate.version>          <org.springframework-version>4.0.3.RELEASE</org.springframework-version>      </properties>      <dependencies>          <dependency>              <groupId>junit</groupId>              <artifactId>junit</artifactId>              <version>4.10</version>              <scope>test</scope>          </dependency>          <dependency>              <groupId>cglib</groupId>              <artifactId>cglib</artifactId>              <version>2.2.2</version>          </dependency>          <dependency>              <groupId>log4j</groupId>              <artifactId>log4j</artifactId>              <version>1.2.14</version>              <scope>provided</scope>          </dependency>          <dependency>              <groupId>mysql</groupId>              <artifactId>mysql-connector-java</artifactId>              <version>5.1.21</version>          </dependency>            <!-- hibernate 4.3.0 start -->          <dependency>              <groupId>org.hibernate</groupId>              <artifactId>hibernate-core</artifactId>              <version>4.3.0.Final</version>          </dependency>          <dependency>              <groupId>org.hibernate.javax.persistence</groupId>              <artifactId>hibernate-jpa-2.0-api</artifactId>              <version>1.0.1.Final</version>          </dependency>          <dependency>              <groupId>org.hibernate</groupId>              <artifactId>hibernate-ehcache</artifactId>              <version>4.3.0.Final</version>          </dependency>          <dependency>              <groupId>org.hibernate</groupId>              <artifactId>hibernate-validator</artifactId>              <version>5.1.0.Alpha1</version>          </dependency>          <dependency>              <groupId>org.hibernate.common</groupId>              <artifactId>hibernate-commons-annotations</artifactId>              <version>4.0.4.Final</version>          </dependency>          <!-- hibernate 4.3.0 end -->          <!-- spring start -->          <dependency>              <groupId>org.springframework</groupId>              <artifactId>spring-context</artifactId>              <version>${org.springframework-version}</version>          </dependency>            <dependency>              <groupId>org.springframework</groupId>              <artifactId>spring-webmvc</artifactId>              <version>${org.springframework-version}</version>          </dependency>          <dependency>              <groupId>org.springframework</groupId>              <artifactId>spring-orm</artifactId>              <version>${org.springframework-version}</version>              <type>jar</type>              <scope>compile</scope>          </dependency>          <!-- spring end -->          <!-- servlet jsp -->          <dependency>              <groupId>javax.servlet</groupId>              <artifactId>javax.servlet-api</artifactId>              <version>3.1.0</version>              <scope>provided</scope>          </dependency>          <dependency>              <groupId>javax.servlet.jsp</groupId>              <artifactId>javax.servlet.jsp-api</artifactId>              <version>2.3.1</version>              <scope>provided</scope>          </dependency>          <dependency>              <groupId>jstl</groupId>              <artifactId>jstl</artifactId>              <version>1.2</version>          </dependency>          <dependency>              <groupId>org.apache.commons</groupId>              <artifactId>commons-dbcp2</artifactId>              <version>2.0</version>          </dependency>          <dependency>              <groupId>commons-logging</groupId>              <artifactId>commons-logging</artifactId>              <version>1.1.1</version>          </dependency>            <dependency>              <groupId>org.springframework</groupId>              <artifactId>spring-orm</artifactId>              <version>${org.springframework-version}</version>              <type>jar</type>              <scope>compile</scope>          </dependency>          <!-- struts2 -->          <dependency>              <groupId>org.apache.struts</groupId>              <artifactId>struts2-core</artifactId>              <version>2.3.1.2</version>          </dependency>          <dependency>              <groupId>org.apache.struts</groupId>              <artifactId>struts2-spring-plugin</artifactId>              <version>2.3.1.2</version>          </dependency>          <!-- struts2注解零配置依赖的包 -->          <dependency>              <groupId>org.apache.struts</groupId>              <artifactId>struts2-convention-plugin</artifactId>              <version>2.3.1</version>          </dependency>          <!-- struts2标签 -->          <dependency>              <groupId>org.apache.struts</groupId>              <artifactId>struts-taglib</artifactId>              <version>1.3.10</version>          </dependency>      </dependencies>      <build>          <finalName>demo</finalName>          <plugins>              <!-- <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId>                   </plugin> -->              <plugin>                  <groupId>org.apache.tomcat.maven</groupId>                  <artifactId>tomcat7-maven-plugin</artifactId>                  <version>2.1</version>                  <configuration>                      <port>8088</port>                  </configuration>              </plugin>            </plugins>      </build>  </project>

2 .spring配置文件 springMVC.xml,这里将hibernate的配置文件:hbm使用注解代替,cfg主配置文件直接在spring配置文件中配置。

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"      xmlns:cache="http://www.springframework.org/schema/cache"      xmlns:context="http://www.springframework.org/schema/context"      xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"      xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"      xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"      xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"      xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"      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-3.2.xsd              http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd              http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd              http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd              http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.2.xsd              http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd              http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd              http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd              http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd              http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">        <context:component-scan base-package="com.syb" />      <!--配置spring 注解 -->      <context:annotation-config />      <!-- 默认的注解映射的支持 -->      <mvc:annotation-driven />      <bean          class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />      <util:properties id="dataSourceProps" location="classpath:./jdbc.properties" />      <bean id="dataSource"          class="org.springframework.jdbc.datasource.DriverManagerDataSource">          <property name="driverClassName">              <value>#{dataSourceProps['jdbc.driverClassName']}</value>          </property>          <property name="url">              <value>#{dataSourceProps['jdbc.url']}</value>          </property>          <property name="username" value="#{dataSourceProps['jdbc.username']}" />          <property name="password" value="#{dataSourceProps['jdbc.password']}" />      </bean>      <!-- 配置数据源 -->      <bean id="transactionManager"          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">          <property name="dataSource" ref="dataSource" />      </bean>      <!-- 事物 -->      <tx:annotation-driven transaction-manager="transactionManager" />        <bean id="sessionFactory"          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">          <property name="dataSource" ref="dataSource" />          <property name="packagesToScan" value="com.syb"></property>          <property name="hibernateProperties">              <props>                  <prop key="hibernate.hbm2ddl.auto">false</prop>                  <prop key="hibernate.show_sql">true</prop>              </props>          </property>      </bean>      <!-- 视图解释类,如果用struts2,则springmvc的配置可不用,加了也没事 -->      <bean          class="org.springframework.web.servlet.view.InternalResourceViewResolver">          <property name="prefix" value="/WEB-INF/pages/" />          <property name="suffix" value=".jsp" />          <property name="viewClass"              value="org.springframework.web.servlet.view.JstlView" />      </bean>      <!-- 处理静态资源 -->      <mvc:resources mapping="/static/**" location="/WEB-INF/static/" />    </beans>

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver  jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8  jdbc.username=root  jdbc.password=root

3 struts.xml的配置文件, 这里将action交给spring管理

<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE struts PUBLIC  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  "http://struts.apache.org/dtds/struts-2.0.dtd">    <struts>      <constant name="struts.enable.DynamicMethodInvocation" value="true" />       <constant name="struts.devMode" value="true"/>      <constant name="struts.i18n.encoding" value="UTF-8" />      <constant name="struts.convention.result.path" value="/WEB-INF/pages"/>      <constant name="struts.convention.package.locators" value="web,action"/>      <constant name="struts.objectFactory" value="spring"/>      <constant name="struts.configuration.xml.reload" value="true"/>  </struts>

4.web.xml,主要配置加载springMVC,struts2过滤器
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">    <context-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath*:/springMVC.xml</param-value>    </context-param>    <listener>      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <filter>      <filter-name>CharacterEncodingFilter</filter-name>      <filter-class>                org.springframework.web.filter.CharacterEncodingFilter            </filter-class>      <init-param>        <param-name>encoding</param-name>        <param-value>utf-8</param-value>      </init-param>    </filter>    <filter-mapping>      <filter-name>CharacterEncodingFilter</filter-name>      <url-pattern>/*</url-pattern>    </filter-mapping>     <!--      <filter>          <filter-name>shiroFilter</filter-name>          <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>          <init-param>              <param-name>targetFilterLifecycle</param-name>              <param-value>true</param-value>          </init-param>      </filter>       <filter-mapping>          <filter-name>shiroFilter</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping> -->    <!--   <servlet>      <servlet-name>spring3mvc</servlet-name>      <servlet-class>                org.springframework.web.servlet.DispatcherServlet            </servlet-class>      <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath*:/springMVC.xml</param-value>      </init-param>      <load-on-startup>2</load-on-startup>    </servlet>    <servlet-mapping>      <servlet-name>spring3mvc</servlet-name>      <url-pattern>/</url-pattern>    </servlet-mapping> -->    <display-name>Struts 2 Web Application</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>/*</url-pattern>      </filter-mapping>      <welcome-file-list>      <welcome-file>/WEB-INF/pages/index.jsp</welcome-file>    </welcome-file-list>  </web-app>

5,实体User如下:

package com.syb.entity;    import java.util.Date;    public class Event {      private Long id;        private String title;      private Date date;        public Event() {}        public Long getId() {          return id;      }        private void setId(Long id) {          this.id = id;      }        public Date getDate() {          return date;      }        public void setDate(Date date) {          this.date = date;      }        public String getTitle() {          return title;      }        public void setTitle(String title) {          this.title = title;      }  }

6Dao层:UserDao.java事务直接加在了dao上,只是为了测试就没问题。

package com.syb.dao;    import java.util.Date;  import java.util.List;    import javax.transaction.Transactional;    import org.hibernate.Session;  import org.hibernate.SessionFactory;  import org.hibernate.Transaction;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.context.ApplicationContext;  import org.springframework.context.support.ClassPathXmlApplicationContext;  import org.springframework.stereotype.Component;    import com.syb.entity.Employee;  @Component  @Transactional  public class UserDao {      @Autowired      SessionFactory sessionFactory;        public static void main(String[] args) {          ApplicationContext context = new ClassPathXmlApplicationContext("springMVC.xml");          SessionFactory factory = (SessionFactory) context.getBean("sessionFactory");          Session session = factory.getCurrentSession();          Transaction transaction =  session.beginTransaction();          for (int i =31; i < 40; i++) {              Employee emp = new Employee();              emp.setName("David"+i);              emp.setRole("Developer"+i);              emp.setInsertTime(new Date());              session.save(emp);          }          session.flush();          transaction.commit();      }      public List<Employee> list() {          return sessionFactory.openSession().createQuery("from Employee").list();      }  }

7最后是action UserAction.java

package com.syb.web;    import org.apache.struts2.ServletActionContext;  import org.apache.struts2.convention.annotation.Action;  import org.apache.struts2.convention.annotation.Result;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.stereotype.Component;    import com.syb.dao.UserDao;  import com.syb.entity.Employee;  @Component  @Action(value="userAction",results= {@Result(name = "success", location = "/WEB-INF/pages/index.jsp")})  public class UserAction {      @Autowired      private UserDao muserDao;  //    @Action(value = "list", results = {@Result(name = "success", location = "/WEB-INF/pages/index.jsp")})      public String list() {          String resultString ="";          for (Employee e:muserDao.list()) {              resultString+=e.getName()+" :"+e.getRole()+"\r\n";          }          ServletActionContext.getRequest().setAttribute("result", resultString);          return "success";      }  }

struts2调用方法的三种方式
1在struts.xml中配置action时指定method
2以感叹号动态调用,要求配置中打开动态方法调用

3以通配符调用(官方推荐)

强调内容
最后直接执行mvn build,因为pom中已经包含了tomcat7,goal中输入:tomcat7:run 即可。
run as 执行mvn build可看到如下