代码改变世界

eclipse配置Struts2、Hibernate3、Spring2.5范例

2013-06-10 23:49  夜雨瞳  阅读(1628)  评论(0编辑  收藏  举报

目录

1       下载eclipse. 1

2       安装HIBERNATE插件.. 1

2.1       安装hibernate synchronizer 1

3       创建项目.. 3

3.1       创建Demo项目.. 3

3.2       JUnit4. 4

3.3       Referenced Libraries 5

4       项目分层概述.. 8

5       demo.core. 9

5.1       Pagination.java. 9

5.2       SpringBaseRootDAO.java. 12

6       demo.model 15

6.1       生成*.hbm.xml 15

6.2       抽象工厂方法.. 19

6.3       生成model 23

7       配置spring-database.xml 24

8       配置spring-dao.xml 26

9       demo.service. 27

10         配置spring-service.xml 27

11         demo.action. 28

12         配置struts.xml 30

13         配置web.xml 31

14         编译.. 33

14.1         引入inst、build.bat、startup.bat 33

14.2         build编译.. 34

14.3         startup编译.. 35

15         运行效果.. 37

16         总结.. 37

 

 

 

1    下载eclipse

官网:http://www.eclipse.org/downloads/

 

2    安装HIBERNATE插件

2.1     安装hibernate synchronizer

下载地址:

http://sourceforge.net/projects/hibernatesynch/?source=navbar

备注:

若有兴趣了解,可进入以下官网详细了解hibernate

http://sourceforge.net/projects/hibernate/?source=recommended或者

http://www.hibernate.org/

 

1)    解压com.hudson.hibernatesynchronizer_3.1.9文件

2)    将com.hudson.hibernatesynchronizer_3.1.9放到eclipse/ plugins

 

3)    运行cmd→进入eclipse文件夹→执行eclipse –clean

使用eclipse –clean进行把当前插件加载进去。

 

3    创建项目

3.1     创建Demo项目

1)    File→New→Java Project→Demo

 

3.2     JUnit4

1)    右键→Build Path→Add Libraries…→JUnit4→Finish

 

3.3     Referenced Libraries

1)    右键→Build Path→Configure Build Path…

 

导入JAR包,即struts2、spring、hibernate包(ssh必须包可以查询相应Web,这里包括了ssh、json序列化包、mysql、servlet等包)

antlr-2.7.7.jar
aopalliance-1.0.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
c3p0-0.9.1.jar
cglib-2.2.2.jar
classworlds-1.1.jar
commons-beanutils-1.7.0.jar
commons-chain-1.2.jar
commons-collections-3.1.jar
commons-dbcp-1.4.jar
commons-digester-2.0.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
commons-pool-1.6.jar
commons-validator-1.3.1.jar
dom4j-1.6.1.jar
ehcache-core-2.4.3.jar
ezmorph-1.0.3.jar
freemarker-2.3.18.jar
hibernate3.jar
jackson-core-asl-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
json-lib-2.1-jdk15.jar
juli-6.0.18.jar
log4j-1.2.16.jar
mysql-connector-java-5.1.18-bin.jar
ognl-3.0.4.jar
org.apache.felix.bundlerepository-1.2.1.jar
org.apache.felix.framework-1.4.1.jar
org.apache.felix.main-1.4.1.jar
org.apache.felix.shell-1.0.2.jar
org.apache.felix.shell.tui-1.0.2.jar
org.springframework.aop-3.1.1.RELEASE.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.aspects-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.context.support-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.instrument-3.1.1.RELEASE.jar
org.springframework.instrument.tomcat-3.1.1.RELEASE.jar
org.springframework.jdbc-3.1.1.RELEASE.jar
org.springframework.jms-3.1.1.RELEASE.jar
org.springframework.orm-3.1.1.RELEASE.jar
org.springframework.oxm-3.1.1.RELEASE.jar
org.springframework.test-3.1.1.RELEASE.jar
org.springframework.transaction-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
org.springframework.web.portlet-3.1.1.RELEASE.jar
org.springframework.web.servlet-3.1.1.RELEASE.jar
org.springframework.web.struts-3.1.1.RELEASE.jar
oro-2.0.8.jar
oscache-2.4.1.jar
oval-1.31.jar
plexus-container-default-1.0-alpha-10.jar
plexus-utils-1.2.jar
servlet-api.jar
sitemesh-2.4.2.jar
struts2-core-2.3.1.2.jar
struts2-jasperreports-plugin-2.3.1.2.jar
struts2-json-plugin-2.3.1.2.jar
struts2-junit-plugin-2.3.1.2.jar
struts2-spring-plugin-2.3.1.2.jar
struts2-testng-plugin-2.3.1.2.jar
struts-core-1.3.10.jar
testng-5.1-jdk15.jar
tiles-api-2.0.6.jar
tiles-core-2.0.6.jar
tiles-jsp-2.0.6.jar
velocity-1.6.3.jar
xpp3_min-1.1.3.4.O.jar
xstream-1.2.2.jar
xwork-core-2.3.1.2.jar

 

 

4    项目分层概述

 

1)    demo.core

Pagination.java(分页工具)

SpringBaseRootDAO.java(基类,使用分页工具进行查询HQL分页)

2)    demo.model

A01.hbm.xml(ORM工具)

A01.java(hibernatesynchronizer 生成:表A01映射对象)

3)    demo.model.base

BaseA01.java(hibernatesynchronizer 生成:表的get set 方法)

BaseA01DAO.java(hibernatesynchronizer 生成:表的获取数据方法)

4)    demo.model.dao

A01DAO.java(hibernatesynchronizer 生成:空方法)

_RootDAO.java(hibernatesynchronizer 生成:空方法)

5)    demo.service

UserService.java(用户服务)

RoleService.java(角色服务)

6)    demo.action

UserAction.java(用户行为访问)

RoleAction.java(用户行为访问)

7)    spring

spring-dao.xml依赖注入,反转控制

spring-database.xml数据库连接

spring-service依赖注入,反转控制

8)    struts2

struts.xml配置<interceptors>拦截器、action访问

9)    xml

web.xml配置<context-param>struts2、spring位置,配置监听spring等。

启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置文件web.xml。

读两个节点: <listener></listener> 和 <context-param></context-param>紧接着,容器创建一个ServletContext(上下文),这个WEB项目所有部分都将共享这个上下文。

5    demo.core

添加以下2个文件:Pagination.java、SpringBaseRootDAO.java

5.1     Pagination.java

import java.io.Serializable;
import java.util.List;
public class Pagination implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 9044906579682916890L;
    protected int currentPageNo;
    protected int totalPageCount;
    protected int totalRecordCount;
    protected List resultSet;
    protected int pageSize = 10;
    protected int first;
    protected int preview;
    protected int next;
    protected int last;

    public int getCurrentPageNo() {
        return currentPageNo;
    }
    public void setCurrentPageNo(int currentPageNo) {
        this.currentPageNo = currentPageNo;
    }
    public int getTotalPageCount() {
        return totalPageCount;
    }
    public void setTotalPageCount(int totalPageCount) {
        this.totalPageCount = totalPageCount;
    }
    public int getTotalRecordCount() {
        return totalRecordCount;
    }
    public void setTotalRecordCount(int totalRecordCount) {
        this.totalRecordCount = totalRecordCount;
    }
    public List getResultSet() {
        return resultSet;
    }
    public void setResultSet(List resultSet) {
        this.resultSet = resultSet;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getFirst() {
        return first;
    }
    public void setFirst(int first) {
        this.first = first;
    }
    public int getPreview() {
        return preview;
    }
    public void setPreview(int preview) {
        this.preview = preview;
    }
    public int getNext() {
        return next;
    }
    public void setNext(int next) {
        this.next = next;
    }
    public int getLast() {
        return last;
    }
    public void setLast(int last) {
        this.last = last;
    }
}

 

5.2     SpringBaseRootDAO.java

package demo.core;
import java.sql.SQLException;
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.Type;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
 
/**
 * Based on Hibernate Synchronizer
 *
 * @author King
 */
public abstract class SpringBaseRootDAO extends HibernateTemplate {

       /**
        * Return the name of the configuration file to be used with this DAO or
        * null if default
        */
       public String getConfigurationFileName() {
              return null;
       }

       /**
        * Return the specific Object class that will be used for class-specific
        * implementation of this DAO.
        *
        * @return the reference Class
        */
       protected abstract Class getReferenceClass();
 
       /**
        * Return a Criteria object that relates to the DAO's table
        */
       protected Criteria createCriteria(Session s) throws DataAccessException {
              return s.createCriteria(getReferenceClass());
       }

       /**
        * Return a Criteria object that relates to the DAO's table
        */
       public Criteria createCriteria() throws HibernateException {
              Session s = getSessionFactory().openSession();
              return s.createCriteria(getReferenceClass());
       }

       /**
        * Return the property of the class you would like to use for default
        * ordering
        *
        * @return the property name
        */
       public String getDefaultOrderProperty() {
              return null;
       }
 
       /**
        * Common Pagination Function
        *
        * @param hql
        * @param pageNo
        * @param pageSize
        * @return
        */
       public Pagination getList(final String hql, final int pageNo,
                     final int pageSize) {
              return (Pagination) execute(new HibernateCallback() {
                     public Object doInHibernate(Session session)
                                   throws HibernateException {
                            Query query = session.createQuery(hql);
                            Pagination pagination = new Pagination();
                            pagination.setCurrentPageNo(pageNo);
                            pagination.setPageSize(pageSize);
                          pagination.setTotalRecordCount(query.list().size());
                            query.setFirstResult(pagination.getPageSize() * (pageNo - 1));
                           query.setMaxResults(pagination.getPageSize());
                            pagination.setResultSet(query.list());
                            return pagination;
                     }
              });
       }
 
       /**
        * Common Pagination Function
        *
        * @param hql
        * @param args
        * @param pageNo
        * @param pageSize
        * @return
        */
       public Pagination getList(final String hql, final Object[] args,
                     final int pageNo, final int pageSize) {
              return (Pagination) execute(new HibernateCallback() {
                     public Object doInHibernate(Session session)
                                   throws HibernateException {
                            Query query = session.createQuery(hql);
                            if (args != null && args.length > 0) {
                                   for (int i = 0; i < args.length; i++)
                                          query.setParameter(i, args[i]);
                            }
                            Pagination pagination = new Pagination();
                            pagination.setCurrentPageNo(pageNo);
                            pagination.setPageSize(pageSize);
                        pagination.setTotalRecordCount(query.list().size());
                            query.setFirstResult(pagination.getPageSize() * (pageNo - 1));
                           query.setMaxResults(pagination.getPageSize());
                            pagination.setResultSet(query.list());
                            return pagination;
                     }
              });
       }
}

 

6    demo.model

6.1     生成*.hbm.xml

10) File→New→Other…

 

jdbc:mysql://localhost:3306/yt4a?useUnicode=true&amp;characterEncoding=utf8

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
       "-//Hibernate/Hibernate Mapping DTD//EN"
       "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="demo.model">
       <class
              name="A01"
              table="a01"
       >
              <meta attribute="sync-DAO">true</meta>
              <id
                     name="A0101"
                     type="int"
                     column="A0101"
              >
                     <generator class="identity"/>
              </id>
              <property
                     name="A0102"
                     column="A0102"
                     type="int"
                     not-null="false"
                     length="10"
              />
              <property
                     name="A0103"
                     column="A0103"
                     type="int"
                     not-null="false"
                     length="10"
              />
              <property
                     name="A0104"
                     column="A0104"
                     type="string"
                     not-null="false"
                     length="100"
              />
              <property
                     name="A0105"
                     column="A0105"
                     type="string"
                     not-null="false"
                     length="500"
              />
              <property
                     name="A0106"
                     column="A0106"
                     type="date"
                     not-null="false"
                     length="19"
              />
              <property
                     name="A0107"
                     column="A0107"
                     type="int"
                     not-null="false"
                     length="10"
              />
              <property
                     name="A0108"
                     column="A0108"
                     type="int"
                     not-null="false"
                     length="10"
              />
       </class>
</hibernate-mapping>

 

6.2     抽象工厂方法

根据抽象工厂方法,打开eclipse的IDE,设置Hibernate Synchronizer

1)    Window→Preferences→Hibernate Synchronizer→Snippets→Root DAO→Class Definition

public abstract class _RootDAO extends demo.core.SpringBaseRootDAO {

 

_RootDAO继承demo.core.SpringBaseRootDAO

2)    Window→Preferences→Hibernate Synchronizer→Snippets→Base DAO→

Class Definition

public abstract class ${class.BaseDAOClassName} extends demo.model.dao._RootDAO {

 

Class Constructors

public ${class.BaseDAOClassName} () {}

 

ActionMethods

    /**
     * Persist the given transient instance, first assigning a generated identifier. (Or using the current value
     * of the identifier property if the assigned generator is used.) 
     * @param ${class.VarName} a transient instance of a persistent class 
     * @return the class identifier
     */
    public ${class.ParentRoot.Id.Property.ObjectClass} save(${class.AbsoluteValueObjectSignatureClassName} ${class.VarName})
#if ($exceptionClass)
        throws ${exceptionClass} {
#else
    {
#end
        return (${class.ParentRoot.Id.Property.ObjectClass}) super.save(${class.VarName});
    }

    /**
     * Either save() or update() the given instance, depending upon the value of its identifier property. By default
     * the instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the
     * identifier property mapping. 
     * @param ${class.VarName} a transient instance containing new or updated state 
     */
    public void saveOrUpdate(${class.AbsoluteValueObjectSignatureClassName} ${class.VarName})
#if ($exceptionClass)
        throws ${exceptionClass} {
#else
    {
#end
        super.saveOrUpdate(${class.VarName});
    }

    /**
     * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
     * instance with the same identifier in the current session.
     * @param ${class.VarName} a transient instance containing updated state
     */
    public void update(${class.AbsoluteValueObjectSignatureClassName} ${class.VarName}) 
#if ($exceptionClass)
        throws ${exceptionClass} {
#else
    {
#end
        super.update(${class.VarName});
    }

 

Finder Methods

#if ($class.ParentRoot.Id)
    public ${class.AbsoluteValueObjectSignatureClassName} load(${class.ParentRoot.Id.Property.AbsoluteSignatureClassName} key)
#if ($exceptionClass)
        throws ${exceptionClass} {
#else
    {
#end
#if ($class.ParentRoot.Id.Property.isPrimitive())
        return (${class.AbsoluteValueObjectSignatureClassName}) load(getReferenceClass(), new ${class.ParentRoot.Id.Property.ObjectClass}(key));
#else
        return (${class.AbsoluteValueObjectSignatureClassName}) load(getReferenceClass(), key);
#end
    }
#end

#if ($class.ParentRoot.Id)
    public ${class.AbsoluteValueObjectSignatureClassName} get(${class.ParentRoot.Id.Property.AbsoluteSignatureClassName} key)
#if ($exceptionClass)
        throws ${exceptionClass} {
#else
    {
#end
#if ($class.ParentRoot.Id.Property.isPrimitive())
        return (${class.AbsoluteValueObjectSignatureClassName}) get(getReferenceClass(), new ${class.ParentRoot.Id.Property.ObjectClass}(key));
#else
        return (${class.AbsoluteValueObjectSignatureClassName}) get(getReferenceClass(), key);
#end
    }
#end

#if ($class.ParentRoot.Id)
    public java.util.List loadAll()
#if ($exceptionClass)
        throws ${exceptionClass} {
#else
    {
#end
        return loadAll(getReferenceClass());
    }
#end

 

3)    Window→Preferences→Hibernate Synchronizer→Snippets→DAO→Class Definition

public class ${class.DAOClassName} extends ${class.BaseDAOClassName}{

 

6.3     生成model

1)    A01.hbm.xml→右键→Hibernate Synchronizer→Synchronizer and Overwrite

 

2)    删除demo.model.dao.iface

7    配置spring-database.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
       default-autowire="byName">

    <!-- dataSource -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/yt4a?useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean> 
    
    <!-- sessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
            <list>
                <value>demo/model/A01.hbm.xml</value>
            </list>  
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.jdbc.batch_size">100</prop>
                <prop key="hibernate.jdbc.fetch_size">100</prop>
                <prop key="hibernate.jdbc.use_streams_for_binary">true</prop>
                <prop key="hibernate.jdbc.batch_versioned_data">true</prop>
                <prop key="hibernate.use_sql_comments">true</prop>
                <prop key="hibernate.query.substitutions">toLowercase=Lower</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

    <!-- transactionManager -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <!-- txProxyTemplate -->
    <bean id="txProxyTemplate" abstract="true"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager" ref="transactionManager"/>
        <property name="transactionAttributes">
            <props>
                <prop key="create*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="bulk*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="find*">PROPAGATION_SUPPORTS,readOnly</prop>
                <prop key="get*">PROPAGATION_SUPPORTS,readOnly</prop>
                <prop key="*">PROPAGATION_NEVER,readOnly</prop>
            </props>
        </property>
    </bean>
</beans>  

 

8    配置spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
       default-autowire="byName">

    <!-- a01DAO --> 
    <bean id="a01DAO" class="demo.model.dao.A01DAO" />
</beans>

 

9    demo.service

创建包demo.service和创建UserService.java

package demo.service;

import java.util.List;
import demo.model.dao.A01DAO;

public class UserService {
    private A01DAO a01Dao;

    public A01DAO getA01dao() {
        return a01Dao;
    }

    public void setA01dao(A01DAO a01dao) {
        this.a01Dao = a01dao;
    }

    public List findAll() throws Exception {
        List list = a01Dao.find("SELECT _a01 FROM A01 _a01");
        return list;
    }
}

 

10       配置spring-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
       default-autowire="byName">
 
     <!-- userService -->
     <bean id="userService" parent="txProxyTemplate">
        <property name="target">
            <bean class="demo.service.UserService" />
        </property>
    </bean>
</beans>

 

11       demo.action

创建包demo.action和UserAction.java

package demo.action;

import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.HashMap;
import java.util.Map;
import demo.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * create by zhyongfeng in 2013.06.06
 * @author Administrator
 *
 */
public class UserAction extends ActionSupport {
    private int number;
    private UserService userService;
    private InputStream inputStream;

    private Map<String, Object> jsonMap ;
    public String findA01All() {    
        try {
            jsonMap= new HashMap<String, Object>();
            jsonMap.put("result", userService.findA01All());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return SUCCESS;
    }
    
    public String findString(){
        inputStream = new StringBufferInputStream(
                "Hello World! This is a text string response from a Struts 2 Action.");
        return SUCCESS;
    }
    
    
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }    
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    public Map<String, Object> getJsonMap() {
        return jsonMap;
    }
    public void setJsonMap(Map<String, Object> jsonMap) {
        this.jsonMap = jsonMap;
    }
}

 

12       配置struts.xml

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

<struts>

    <!-- <constant name="struts.custom.i18n.resources" value="message"/> -->
    <constant name="struts.i18n.encoding" value="utf-8" />
    <constant name="struts.objectFactory" value="spring" />
    <constant name="struts.multipart.parser" value="Jakarta" />
    <constant name="struts.multipart.maxSize" value="1000000000" />

    <package name="demo" extends="json-default" namespace="/">

        <interceptors>
            <interceptor-stack name="managerStack">
                <interceptor-ref name="staticParams" />
                <interceptor-ref name="params" />
                <!--<interceptor-ref name="authorize" />-->
                <interceptor-ref name="chain" />
            </interceptor-stack>

        </interceptors>

        <global-results>
            <result name="login" type="chain">
                <param name="actionName">index.htm</param>
                <param name="namespace">/</param>
            </result>
        </global-results>
 
        <!-- findA01All interceptor是拦截器,可以自己定义拦截器进行用户登录验证-->
        <action name="findA01All" class="demo.action.UserAction"
            method="findA01All">
            <result type="json">
                <param name="root">jsonMap</param>
                <param name="excludeNullProperties">true</param>
            </result>
            <interceptor-ref name="params" />
        </action>
        
        <!-- findString -->
        <action name="findString" class="demo.action.UserAction"
            method="findString">
            <result type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>
            <interceptor-ref name="params" />
        </action>
    </package>
    
    <!-- html files -->
    <include file="struts-htm.xml" />
</struts>

 

13       配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    
    <display-name>Demo</display-name>
    
    <context-param> 
        <param-name>webAppRootKey</param-name> 
        <param-value>web.root</param-value> 
    </context-param>    
    
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/conf/log4j.properties</param-value>
    </context-param>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/conf/spring/*.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 
    </listener>    
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>    
    
    <filter>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    </filter>
    
    <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>
    </filter>
    
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <welcome-file-list>
        <welcome-file>index.htm</welcome-file>      
    </welcome-file-list>
</web-app>

 

14       编译

14.1        引入inst、build.bat、startup.bat

 

根据实际情况修改以下路径: D:\JDK、D:\TOMCAT7、D:\PROJECTS\JAVA\。

inst\conf\server.xml

<Host name="localhost" unpackWARs="true"> 
<Context path="" docBase="D:/PROJECTS/JAVA/Demo/htdocs" reloadable="true" workDir="D:/PROJECTS/JAVA/YT4A/htdocs/work" />
</Host>

 

build.xml

(将会打包放在WEB-INF/lib下)

<property name="jarfile" value="${web.dir}/WEB-INF/lib/${name}-${version}.jar" />

 

Startup.bat

set JAVA_HOME=D:\JDK
set CATALINA_HOME=D:\TOMCAT7
set CATALINA_BASE=D:\PROJECTS\JAVA\Demo\inst

SET JPDA_ADDRESS=8000
SET JPDA_TRANSPORT=dt_socket

%CATALINA_HOME%\bin\catalina.bat jpda start

14.2        build编译

通过cmd,进行到demo,执行build.bat

D:\PROJECTS\JAVA\Demo>ant -f build.xml
Buildfile: D:\PROJECTS\JAVA\Demo\build.xml

usage:
     [echo]
     [echo] demo build file
     [echo] -----------------------------------
     [echo]
     [echo] Available targets are:
     [echo]
     [echo] prepare   --> Prepare for clean build
     [echo] build     --> Build the application
     [echo] jar       --> Create java jar file
     [echo] deploy    --> Deploy application
     [echo] dist      --> Create binary distribution
     [echo]

prepare:
   [delete] Deleting directory D:\PROJECTS\JAVA\Demo\bin

compile:
    [mkdir] Created dir: D:\PROJECTS\JAVA\Demo\bin
    [javac] D:\PROJECTS\JAVA\Demo\build.xml:48: warning: 'includeantruntime' was
 not set, defaulting to build.sysclasspath=last; set to false for repeatable bui
lds
    [javac] Compiling 9 source files to D:\PROJECTS\JAVA\Demo\bin
    [javac] 注: D:\PROJECTS\JAVA\Demo\src\demo\action\UserAction.java使用或覆盖
了已过时的 API。
    [javac] 注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。
    [javac] 注: 某些输入文件使用了未经检查或不安全的操作。
    [javac] 注: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。
     [copy] Copying 3 files to D:\PROJECTS\JAVA\Demo\bin

jar:
      [jar] Building jar: D:\PROJECTS\JAVA\Demo\htdocs\WEB-INF\lib\demo-1.0.jar

deploy:

BUILD SUCCESSFUL
Total time: 1 second

D:\PROJECTS\JAVA\Demo>

 

14.3        startup编译

运行startup

 

15       运行效果

 

 

16       总结

本文主要依据以下链接进行配置:

http://www.supergloo.com/blog/index.php/category/hibernate-synchronizer/

 

资料下载:

Apache ANT官网:http://ant.apache.org/bindownload.cgi

Tomcat官网:http://tomcat.apache.org/

JDK官网:http://www.oracle.com/technetwork/java/javase/downloads/index.html

Eclipse官网:http://www.eclipse.org/downloads/

hibernate synchronizer:http://sourceforge.net/projects/hibernatesynch/?source=navbar

 

(详细代码请参照Demo例子)

进行本配置,只需要解压Apache ANT、Tomcat、Eclipse、hibernate synchronizer和安装JDK,通过build.bat、startup.bat便可以开启编译程序。

DEMO源码下载:http://dl.vmall.com/c0a5kbff7h

PDF下载:https://files.cnblogs.com/yongfeng/20130610.pdf