eclipse搭建web项目开发环境

下面是一个jpa2+eclipselinkstruts2spring的框架

工具:

  eclipse、tomcat、mysql、jdk

jar包:

  struts2:注意版本尽量一致。

  eclipselink:eclipselink.jar。忘了ejb3-persistence.jar这个包需不需要加了,还是加上吧

  spring:可以搜索一下每个jar包的作用,为了省事就全部加进来,还有aopalliance.jar这个包。与spring整合的适合加上struts2-spring-plugin-2.3.1.2.jar

  json、dom、log相关的jar:ezmorph-1.0.6.jar、jdom-2.0.5.jar、dom4j-1.6.1.jar、json-lib-2.3-jdk15.jar、log4j-1.2.14.jar

  数据库驱动包:mysql-connector-java-5.1.7-bin.jar

  commons工具包:要有哪些加哪些如:commons-beanutils-1.9.1.jar、commons-codec-1.9.jar、commons-collections4-4.0.jar、commons-lang3-3.2.1.jar

准备工作:

  下载好软件安装、jar包、创建好测试数据库及表、调好eclipse字体(eclipse[Version: Indigo Service Release 2]默认字体中文显示太小调成5号就好点了),

  打开eclipse加入user lib web需要的jar包:javaee的jar包,,这几个包我是从myeclipse中拷贝来的,可以下载到

1,新建Dynamic Web Project 名字model1,将项目编码改为utf-8,在java build path中加入上面添加的那个javaee user lib

2,

  (1)配置eclipselink:新建一个source folder config,在config下新建META-INF目录,在META-INF下新建persistence.xml

  persistence.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="test_pu" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
          <class>net.codeodel.po.AgencyInfo</class>  
        <properties>
          <property name="javax.persistence.jdbc.driver"   value="com.mysql.jdbc.Driver" /> 
          <property name="javax.persistence.jdbc.url"      value="jdbc:mysql://localhost:3306/ims" />
          <property name="javax.persistence.jdbc.user"     value="root" />
          <property name="javax.persistence.jdbc.password" value="root" />
        </properties>
    </persistence-unit>

</persistence>

  (2)配置spring:在config下新建applicationContext.xml
applicationContext.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
    http://www.springframework.org/schema/tx      
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
<!--scan    -->
    <context:component-scan base-package="net.codeodel" ></context:component-scan>
        
<!--jpa    -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="test_pu" />
    </bean>
    
    
<!--jpa事物管理    -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    
<!--使用注解标明事物    -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    
</beans>

  (3)配置struts2(及国际化的实现):在config下新建struts.xml

struts.xml内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts>
    
    <constant name="struts.objectFactory" value="spring" />
    <!-- 上传文件大小 -->
    <constant name="struts.multipart.maxSize" value="1000000000" ></constant>
    <constant name="struts.action.extension" value="action" />
    <constant name="struts.ognl.allowStaticMethodAccess" value="true" />
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.i18n.encoding" value="utf-8" />
    <!-- 国际化 -->
    <constant name="struts.locale" value="zh_CN" />
    <constant name="struts.custom.i18n.resources" value="Message" />
    <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,开发阶段最好打开 -->    
    <constant name="struts.configuration.xml.reload" value="true" />
    <!-- 设置浏览器是否缓存静态内容,默认为TRUE  开发阶段最好关闭 -->
    <constant name="struts.server.static.browserCache" value ="false"/>
    <!-- 便于排错,打印出更详细的错误信息 -->
    <constant name="struts.devMode" value="true" />
    
    <package name="base-json" extends="json-default">
        
    </package>
    
    <include file="struts/*.xml" />

</struts>    

在config下新建struts文件夹,之后的所有action对应的struts配置都放在这个目录下
在config下新建Message_zh_CN.properties这里是国际化用的(在action中取值可以用getText,action要继承了actionsupport才能取到,页面采用标签获取)

(4)配置log4j:在config下新建log4j.properties

log4j.properties的内容如下:

# Global logging configuration
log4j.rootLogger=ERROR, fileout

#shutdown framework log
log4j.logger.org.springframework=ERROR
log4j.logger.com.opensymphony=ERROR
log4j.logger.org.apache=ERROR
log4j.logger.org.logicalcobwebs=ERROR
log4j.logger.freemarker.cache=ERROR
log4j.logger.freemarker.beans=ERROR

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern=[%p,%c{1},%t] %m%n

# Rolling log file output...
log4j.appender.logfile.DatePattern=.yyyy-MM-dd
log4j.appender.fileout=org.apache.log4j.RollingFileAppender
log4j.appender.fileout.File=${model1.root}/j2eetestout.log
log4j.appender.fileout.MaxFileSize=1024KB
log4j.appender.fileout.MaxBackupIndex=1
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c,%t:%L - %m%n

这个配置是随便找来的,那个${model1.root}是在web.xml中有配置,是项目发布后的绝对路径
(5)配置web.xml

web.xml配置如下:

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    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_2_5.xsd">
    
    
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>model1.root</param-value>
    </context-param>

    <!-- spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    
    <!-- 利用spring,实现不用关闭工程更改log4j的配置,-->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    
    <!-- spring 统一使用utf-8 防止中文乱码 -->
    <filter>
        <filter-name>CharsetFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharsetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- struts2 -->
    <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>
    <filter>
        <filter-name>action cleanup</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>action cleanup</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

    <!-- session -->
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>

</web-app>

 

 

整个框架基本的东西就ok了

下面是basedao的示例:

package net.codeodel.dao;

import java.util.List;

public interface BaseDAO  {
    /**
     * 查询对象
     * @param clz 对象类
     * @param id 
     */
    public <T> T getObject(Class<T> clz, Object id) ; 
    
    /**
     * 查询对象列表
     * @param page 分页用
     */
    public List<?> findObject(final String ql, final List<Object> paramList, final int... page) ; 
    
    /**
     * 查询对象总数
     */
    public int getObjectCount(final String ql, final List<Object> paramList) ; 
    
    /**
     * 新增对象
     * @param obj
     */
    public void addObject(Object obj) ; 
    
    /**
     * 修改对象
     * @param obj
     */
    public <T> T updObject(T t) ; 
    
    /**
     * 添加或修改
     * @param obj
     */
    public Object mergeObject(Object obj) ; 
    
    /**
     * 删除对象
     * @param obj
     */
    public void delObject(Object obj) ; 
    
    
    
    /**
     * 执行ql
     * @param ql
     * @param paramList
     */
    public int exec(final String ql, final List<Object> paramList) ;
    
}

baseDaoImpl:

package net.codeodel.daoImpl;


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import net.codeodel.dao.BaseDAO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;

public class BaseDAOImpl implements BaseDAO {
    
    private JpaTemplate jpaTemplate;

    @Autowired
    public void setEntityManagerFactory(EntityManagerFactory emf) {
        this.jpaTemplate = new JpaTemplate(emf);
    }

    public JpaTemplate getJpaTemplate() {
        return jpaTemplate;
    }
    
    @Override
    public void addObject(Object obj) {
        getJpaTemplate().persist(obj) ; 
    }

    @Override
    public void delObject(Object obj) {
        getJpaTemplate().remove(obj) ; 
    }

    @Override
    public <T> T getObject(Class<T> clz, Object id) {
        return getJpaTemplate().find(clz, id) ; 
    }
    
    @Override
    public Object mergeObject(Object obj) {
        return getJpaTemplate().merge(obj) ; 
    }

    @Override
    public <T> T updObject(T t) {
//        if( t.getId() == null ){
//            throw new RuntimeException("ID不能为空") ; 
//        }
        return getJpaTemplate().merge(t) ; 
    }

    @SuppressWarnings("unchecked")
    @Override
    public List findObject(final String ql, final List<Object> paramList, final int... page) {
        
        List ret = getJpaTemplate().executeFind(new JpaCallback() {
            @Override
            public List doInJpa(EntityManager em)
                    throws PersistenceException {
                
                Query q = em.createQuery(ql) ; 
                int counter = 1 ; 
                if( paramList != null ){
                    for (Object o : paramList) {
                        q.setParameter(counter++, o) ; 
                    }
                }
                
                if( page != null && page.length == 2 ){
                    int startRow = page[0] ; 
                    int pageSize = page[1] ; 
                    if(startRow>=0){
                        q.setFirstResult(startRow);
                    }
                    if(pageSize>0){
                        q.setMaxResults(pageSize);
                    }
                }
                
                return q.getResultList();
            }
        }) ; 
        
        return ret ;
    }
    
    @Override
    public int getObjectCount(final String ql, final List<Object> paramList) {
        
        List ret = getJpaTemplate().executeFind(new JpaCallback() {
            @Override
            public List doInJpa(EntityManager em)
                    throws PersistenceException {
                
                Query q = em.createQuery(ql) ; 
                int counter = 1 ; 
                if( paramList != null ){
                    for (Object o : paramList) {
                        q.setParameter(counter++, o) ; 
                    }
                }
                return q.getResultList();
            }
        }) ; 
        
        if( ret.size() == 0 ){
            return 0 ; 
        }
        return Integer.parseInt( ret.get(0).toString() ) ;  
    }
    
    @Override
    public int exec(final String ql, final List<Object> paramList) {
        
        Integer ret = (Integer) getJpaTemplate().execute(new JpaCallback() {
            @Override
            public Integer doInJpa(EntityManager em)
                    throws PersistenceException {
                
                Query q = em.createQuery(ql) ; 
                int counter = 1 ; 
                if( paramList != null ){
                    for (Object o : paramList) {
                        q.setParameter(counter++, o) ; 
                    }
                }
                return q.executeUpdate() ; 
            }
        }) ; 
        return ret ; 
    }

    

}

 

 

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。