zoukankan      html  css  js  c++  java
  • EJB结合struts2创建项目、发布jboss服务器和访问、父类(BaseDaoImpl)的封装

    一、环境搭建:

      1、准备jboss服务器,将对应数据库的xml配置好放到jboss的发布目录下。

    <?xml version="1.0" encoding="UTF-8"?>
    <datasources>
      <local-tx-datasource>
        <jndi-name>MySqlDS</jndi-name>
        <connection-url>jdbc:mysql://192.168.1.11:3306/test?useUnicode=true&amp;characterEncoding=utf-8</connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <user-name>root</user-name>
        <password>root</password>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
        <metadata>
           <type-mapping>mySQL</type-mapping>
        </metadata>
      </local-tx-datasource>
    </datasources>

      2、创建普通的java项目

        在该项目的src目录下的META-INF目录下创建persistence.xml文件(名称不能改变),文件内容如下,发布之后通过jndi名称(MySqlDS)就可以找到数据源。

    <?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="UnitMySql">
            <jta-data-source>java:/MySqlDS</jta-data-source>
            <mapping-file>META-INF/mapping.xml</mapping-file>
            <exclude-unlisted-classes>true</exclude-unlisted-classes>
            <properties>
                <property name="hibernate.hbm2ddl.auto" value="update" />
                <property name="hibernate.show_sql" value="true" />
                <!-- <property name="hibernate.format_sql" value="false" /> -->
            </properties>
        </persistence-unit>
    </persistence>

        mapping.xml文件里面只有是实体类映射

    <?xml version="1.0" encoding="UTF-8"?>
    <entity-mappings version="1.0" 
        xmlns="http://java.sun.com/xml/ns/persistence/orm" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd ">
        <entity class="com.net.entity.User"></entity> ....
        
    </entity-mappings>

      3、在src目录下创建 jndi.properties

    java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
    java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
    java.naming.provider.url=localhost:1099
    public static Object getEJB(String jndipath) {
            try {
                Properties props = new Properties();
                props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
                props.setProperty("java.naming.provider.url", "localhost:1099");
                props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
                InitialContext ctx = new InitialContext(props);
                return ctx.lookup(jndipath);
            }catch(NamingException ex) {
                ex.printStackTrace();
            }
            return null;
        }

    二、准备ejb的service层和dao层:

      1、父类封装:

    public interface BaseDao<T> {
    
        public void setOrderBy(String orderBy);
    
        public void save(T t) throws DAOException;
    
        public void update(T t) throws DAOException;
    
        public void delete(T t) throws DAOException;
    
        public void delete(Collection<T> list) throws DAOException;
    
        public void delete(Serializable id) throws DAOException;
    
        public void delete(String[] ids) throws DAOException;
    
        public T find(Serializable id) throws DAOException;
    
        /**
         * 获取信息数量
         * 
         * @param id
         *            实体id
         * @return
         * @throws DAOException
         */
        public Long findCount() throws DAOException;
    
        /**
         * 获取所有实体类列表
         * 
         * @return
         * @throws DAOException
         */
        public List<T> findAll() throws DAOException;
    
        /**
         * 获取信息分页
         * 
         * @param condition
         *            查询条件
         * @param currentPage
         *            当前页
         * @param pageCount
         *            每页数据行数
         * @return 分页信息
         * @throws DAOException
         */
        public PageInfo<T> findPageInfo(Integer currentPage, Integer pageCount) throws DAOException;
    
        /**
         * 获取信息列表By条件
         * 
         * @param condition
         *            查询条件
         * @return 信息列表
         * @throws DAOException
         */
        public Long findCountByCondation(String condition) throws DAOException;
    
        /**
         * 获取信息列表By条件
         * 
         * @param condition
         *            查询条件
         * @return 信息列表
         * @throws DAOException
         */
        public List<T> findListByCondation(String condition) throws DAOException;
    
        /**
         * 获取信息列表By条件
         * 
         * @param condition
         *            查询条件
         * @param currentPage
         *            当前页
         * @param pageCount
         *            每页数据行数
         * @return 信息列表
         * @throws DAOException
         */
        public List<T> findListByCondation(String condition, Integer currentPage, Integer pageCount) throws DAOException;
    
        /**
         * 获取信息分页By条件
         * 
         * @param condition
         *            查询条件
         * @param currentPage
         *            当前页
         * @param pageCount
         *            每页数据行数
         * @return 分页信息
         * @throws DAOException
         */
        public PageInfo<T> findPageInfoByCondation(String condition, Integer currentPage, Integer pageCount) throws DAOException;
    
        /**
         * 获取信息列表By条件
         * 
         * @param condition
         *            查询条件
         * @return 信息列表
         * @throws DAOException
         */
        public Long findCountByNativeCondation(StringBuffer condition) throws DAOException;
    
        /**
         * 获取信息列表By条件
         * 
         * @param condition
         *            查询条件
         * @return 信息列表
         * @throws DAOException
         */
        public List<?> findListByNativeCondation(StringBuffer condition) throws DAOException;
    
        /**
         * 获取信息列表By条件
         * 
         * @param condition
         *            查询条件
         * @param currentPage
         *            当前页
         * @param pageCount
         *            每页数据行数
         * @return 信息列表
         * @throws DAOException
         */
        public List<?> findListByNativeCondation(StringBuffer condition, Integer currentPage, Integer pageCount) throws DAOException;
    
        /**
         * 获取信息分页By条件
         * 
         * @param condition
         *            查询条件
         * @param currentPage
         *            当前页
         * @param pageCount
         *            每页数据行数
         * @return 分页信息
         * @throws DAOException
         */
        public PageInfo<?> findPageInfoByNativeCondation(StringBuffer condition, Integer currentPage, Integer pageCount) throws DAOException;
    
        public PageInfo<T> findPageInfoBySql(String sql, String countsql, Integer currentPage, Integer pageCount) throws DAOException;
    
        public Long findCountByProperties(String condition, Map<String, Object> map) throws DAOException;
    
        public List<T> findListByProperties(String condition, Map<String, Object> map) throws DAOException;
    
        public List<T> findListByProperties(String condition, Integer currentPage, Integer pageCount, Map<String, Object> map) throws DAOException;
    
        public PageInfo<T> findPageInfoByProperties(String condition, Integer currentPage, Integer pageCount, Map<String, Object> map) throws DAOException;
    
        public <E> List<E> findListByNativeQuery(String sql, Class<E> clazz) throws DAOException;
    
        /**
         * 查询对象是否存在
         * 
         * @param id
         *            对象id
         * @return
         * @throws DAOException
         */
        public boolean isEmpty(String id) throws DAOException;
        /**
         * 
         * sql
         * @param <E>
         * @param tablename 数据库对应表名
         * @param clazz 映射的实体类
         * @param sql 查询语句
         * @param wheresql 查询语句where后面部分
         * @param currentPage 当前页
         * @param pageCount 每页数量
         * @return
         * @throws DAOException
         */
        public <E> PageInfo<E> findPageInfoByNativeQuery(Class<E> clazz,String sql,  String wheresql, Integer currentPage, Integer pageCount) throws DAOException ;
    }
    View Code
    public abstract class BaseDaoBean<T> implements BaseDao<T> {
    
        protected static final Logger logger = Logger.getLogger(BaseDaoBean.class);
        protected String orderBy;
    
        /** 实体类 */
        protected Class<T> entityClass;
        /** 实体类类名 */
        protected String entityClassName;
    
        protected EntityManager entityManager;
    
        @Override
        public void save(T t) throws DAOException {
            entityManager.persist(t);
        }
    
        @Override
        public void update(T t) throws DAOException {
            entityManager.merge(t);
        }
    
        @Override
        public void delete(T t) throws DAOException {
            entityManager.remove(t);
        }
    
        @Override
        public void delete(Collection<T> list) throws DAOException {
            for (T t : list) {
                entityManager.remove(t);
            }
        }
    
        @Override
        public void delete(Serializable id) throws DAOException {
            entityManager.remove(entityManager.getReference(entityClass, id));
        }
    
        @Override
        public void delete(String[] ids) throws DAOException {
            if (ids != null && ids.length != 0) {
                for (String id : ids) {
                    entityManager.remove(entityManager.getReference(entityClass, id));
                }
            }
        }
    
        @Override
        public T find(Serializable id) throws DAOException {
            return entityManager.find(entityClass, id);
        }
    
        @Override
        public Long findCount() throws DAOException {
            return findCountByCondation(null);
        }
    
        @Override
        public List<T> findAll() throws DAOException {
            return findListByCondation(null, null, null);
        }
    
        @Override
        public PageInfo<T> findPageInfo(Integer currentPage, Integer pageCount) throws DAOException {
            return findPageInfoByCondation(null, currentPage, pageCount);
        }
    
        @Override
        public Long findCountByCondation(String condition) throws DAOException {
            StringBuffer sql = new StringBuffer("SELECT COUNT(t.id) FROM " + entityClassName + " t ");
            if (condition != null && !condition.isEmpty()) {
                sql.append(condition);
            }
    
            logger.debug("sql:" + sql);
            Long count = (Long) entityManager.createQuery(sql.toString()).getSingleResult();
            return count;
        }
    
        @Override
        public List<T> findListByCondation(String condition) throws DAOException {
            return findListByCondation(condition, null, null);
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public List<T> findListByCondation(String condition, Integer currentPage, Integer pageCount) throws DAOException {
            StringBuffer sql = new StringBuffer("SELECT t FROM " + entityClassName + " t ");
            if (condition != null && !condition.isEmpty()) {
                sql.append(condition);
            }
    
            if (orderBy != null && !orderBy.isEmpty()) {
                sql.append(" ORDER BY " + orderBy);
            }
            logger.debug("sql:" + sql);
            Query query = entityManager.createQuery(sql.toString());
            if (currentPage != null && pageCount != null) {
                query.setFirstResult((currentPage - 1) * pageCount);
                query.setMaxResults(pageCount);
            }
            return query.getResultList();
        }
    
        @Override
        public PageInfo<T> findPageInfoByCondation(String condition, Integer currentPage, Integer pageCount) throws DAOException {
            Long dataCountMax = this.findCountByCondation(condition);
            List<T> tList = this.findListByCondation(condition, currentPage, pageCount);
            PageInfo<T> pageInfo = new PageInfo<T>(currentPage, pageCount, dataCountMax.intValue(), tList);
            return pageInfo;
        }
    
        public static void main(String[] args) {
            Object o = new BigInteger("123123");
            System.out.println(o);
            System.out.println(o.getClass());
            BigInteger bi = (BigInteger) o;
            System.out.println(bi);
    
        }
    
        @Override
        public Long findCountByNativeCondation(StringBuffer condition) throws DAOException {
            if (condition == null) {
                return 0L;
            }
            StringBuffer sql = new StringBuffer("SELECT COUNT(1) FROM ( ");
            sql.append(condition);
            sql.append(" ) countNum ");
    
            logger.debug("sql:" + sql);
            Object o = entityManager.createNativeQuery(sql.toString()).getSingleResult();
            Long count = 0L;
            if (o instanceof BigInteger) {
                count = ((BigInteger) o).longValue();
            } else {
                count = (Long) entityManager.createNativeQuery(sql.toString()).getSingleResult();
            }
            return count;
        }
    
        @Override
        public List<?> findListByNativeCondation(StringBuffer condition) throws DAOException {
            return findListByNativeCondation(condition, null, null);
        }
    
        @Override
        public List<?> findListByNativeCondation(StringBuffer sql, Integer currentPage, Integer pageCount) throws DAOException {
            if (orderBy != null && !orderBy.isEmpty()) {
                sql.append(" ORDER BY " + orderBy);
            }
            logger.debug("sql:" + sql);
            Query query = entityManager.createNativeQuery(sql.toString());
            if (currentPage != null && pageCount != null) {
                query.setFirstResult((currentPage - 1) * pageCount);
                query.setMaxResults(pageCount);
            }
            return query.getResultList();
        }
    
        @Override
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public PageInfo<?> findPageInfoByNativeCondation(StringBuffer condition, Integer currentPage, Integer pageCount) throws DAOException {
            Long dataCountMax = this.findCountByNativeCondation(condition);
            List<?> tList = this.findListByNativeCondation(condition, currentPage, pageCount);
            PageInfo<?> pageInfo = new PageInfo(currentPage, pageCount, dataCountMax.intValue(), tList);
            return pageInfo;
        }
    
        @Override
        public Long findCountByProperties(String condition, Map<String, Object> map) throws DAOException {
            StringBuffer sql = new StringBuffer("SELECT COUNT(t.id) FROM " + entityClassName + " t ");
            if (condition != null && !condition.isEmpty()) {
                sql.append(condition);
            }
    
            logger.debug("sql:" + sql);
            if (map != null) {
                for (Object value : map.values()) {
                    logger.debug("map:" + value);
                }
            }
            Query query = entityManager.createQuery(sql.toString());
            if (map != null) {
                for (String key : map.keySet()) {
                    query.setParameter(key, map.get(key));
                }
            }
            Long count = (Long) query.getSingleResult();
            return count;
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public PageInfo<T> findPageInfoBySql(String sql, String countsql, Integer currentPage, Integer pageCount) throws DAOException {
            Long count = (Long) entityManager.createQuery(countsql).getSingleResult();
            if (orderBy != null && !orderBy.isEmpty()) {
                sql += " ORDER BY " + orderBy;
            }
            Query query = entityManager.createQuery(sql);
            if (currentPage != null && pageCount != null) {
                query.setFirstResult((currentPage - 1) * pageCount);
                query.setMaxResults(pageCount);
            }
            return new PageInfo<T>(currentPage, pageCount, count.intValue(), query.getResultList());
        }
    
        @Override
        public List<T> findListByProperties(String condition, Map<String, Object> map) throws DAOException {
            return findListByProperties(condition, null, null, map);
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public List<T> findListByProperties(String condition, Integer currentPage, Integer pageCount, Map<String, Object> map) throws DAOException {
            StringBuffer sql = new StringBuffer("SELECT t FROM " + entityClassName + " t ");
            if (condition != null && !condition.isEmpty()) {
                sql.append(condition);
            }
    
            if (orderBy != null && !orderBy.isEmpty()) {
                sql.append(" ORDER BY " + orderBy);
            }
            logger.debug("sql:" + sql);
            if (map != null) {
                for (Object value : map.values()) {
                    logger.debug("map:" + value);
                }
            }
            Query query = entityManager.createQuery(sql.toString());
            if (currentPage != null && pageCount != null) {
                query.setFirstResult((currentPage - 1) * pageCount);
                query.setMaxResults(pageCount);
            }
            if (map != null) {
                for (String key : map.keySet()) {
                    query.setParameter(key, map.get(key));
                }
            }
    
            return query.getResultList();
        }
    
        @Override
        public PageInfo<T> findPageInfoByProperties(String condition, Integer currentPage, Integer pageCount, Map<String, Object> map) throws DAOException {
            Long dataCountMax = this.findCountByProperties(condition, map);
            List<T> tList = this.findListByProperties(condition, currentPage, pageCount, map);
            PageInfo<T> pageInfo = new PageInfo<T>(currentPage, pageCount, dataCountMax.intValue(), tList);
            return pageInfo;
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public <E> List<E> findListByNativeQuery(String sql, Class<E> clazz) throws DAOException {
            return entityManager.createNativeQuery(sql, clazz).getResultList();
        }
        
        @Override
        @SuppressWarnings("unchecked")
        public <E> PageInfo<E> findPageInfoByNativeQuery(Class<E> clazz,String sql,  String wheresql, Integer currentPage, Integer pageCount) throws DAOException {
            Long count = (Long)entityManager.createQuery("SELECT COUNT(*) FROM "+clazz.getSimpleName()+" t  WHERE 1=1 "+wheresql).getSingleResult();
            if (orderBy != null && !orderBy.isEmpty()) {
                wheresql += " ORDER BY " + orderBy;
            }
            Query query = entityManager.createNativeQuery(sql+wheresql,clazz);
            if (currentPage != null && pageCount != null) {
                query.setFirstResult((currentPage - 1) * pageCount);
                query.setMaxResults(pageCount);
            }
            
            return new PageInfo<E>(currentPage, pageCount, count.intValue(), query.getResultList());
            
        }
    
        @Override
        public boolean isEmpty(String id) throws DAOException {
            if (find(id) == null) {
                return true;
            }
            return false;
        }
    
        @SuppressWarnings("unchecked")
        public BaseDaoBean() {
            // getClass() 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的超类的 Class。
            this.entityClass = (Class<T>) getSuperClassGenricType(getClass(), 0);
            this.entityClassName = entityClass.getSimpleName();
        }
    
        @SuppressWarnings("all")
        protected static Class<Object> getSuperClassGenricType(final Class<?> clazz, final int index) {
            // 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
            Type genType = clazz.getGenericSuperclass();
            if (!(genType instanceof ParameterizedType)) {
                return Object.class;
            }
            // 返回表示此类型实际类型参数的 Type 对象的数组。
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            if (index >= params.length || index < 0) {
                return Object.class;
            }
            if (!(params[index] instanceof Class)) {
                return Object.class;
            }
            return (Class<Object>) params[index];
        }
    
        @Override
        public void setOrderBy(String orderBy) {
            this.orderBy = orderBy;
        }
    
        public abstract void setEntityManager(EntityManager entityManager);
    
    }
    View Code
    public class PageInfo<T> implements Serializable, Cloneable {
        private static final Logger logger = Logger.getLogger(PageInfo.class);
    
        private static final long serialVersionUID = -4940465203107135908L;
        /** 当前页码 */
        private Integer currentPage;
        /** 每页数据行数 */
        private Integer pageCount;
        /** 数据总条数 */
        private Integer dataCountMax;
        /** 最大页码 */
        private Integer pageMax;
        /** 实体集合 */
        private List<T> list;
        /** 是否有上一页 */
        private Boolean hasPrev;
        /** 是否有下一页 */
        private Boolean hasNext;
        /** 显示的页数集合 */
        private List<Integer> listPaginDisplay = null;
    
        public List<Integer> getListPaginDisplay() {
            return listPaginDisplay;
        }
    
        public void setListPaginDisplay(List<Integer> listPaginDisplay) {
            this.listPaginDisplay = listPaginDisplay;
        }
    
        public PageInfo() {
    
        }
    
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    
        /**
         * @param currentPage
         *            当前页码
         * @param pageCount
         *            每页数据行数
         * @param dataCountMax
         *            数据总条数
         */
        public PageInfo(Integer currentPage, Integer pageCount, Integer dataCountMax) {
            this.currentPage = currentPage;
            this.pageCount = pageCount;
            this.dataCountMax = dataCountMax;
            this.setParameters();
        }
    
        /**
         * @param currentPage
         *            当前页码
         * @param pageCount
         *            每页数据行数
         * @param dataCountMax
         *            数据总条数
         * @param list
         *            分页后list
         */
        public PageInfo(Integer currentPage, Integer pageCount, Integer dataCountMax, List<T> list) {
            this.currentPage = currentPage;
            this.pageCount = pageCount;
            this.dataCountMax = dataCountMax;
            this.setParameters();
            this.list = list;
        }
    
        /** 重新加载数据信息 */
        public void setParameters() {
            if (currentPage == null) {
                currentPage = 1;
            }
            if (pageCount == null || pageCount < 1) {
                logger.warn("pageCount = 0, setPageCount=100");
                pageCount = 100;
            }
            if (dataCountMax == null) {
                dataCountMax = 10;
            }
    
            this.pageMax = dataCountMax % pageCount == 0 ? (dataCountMax / pageCount) : (dataCountMax / pageCount + 1);
    
            if (currentPage > pageMax) {
                currentPage = pageMax;
            }
    
            this.hasPrev = currentPage > 1 ? true : false;
            this.hasNext = pageMax > currentPage ? true : false;
        }
    
        /**
         * @return the currentPage
         */
        public Integer getCurrentPage() {
            return currentPage;
        }
    
        /**
         * @param currentPage
         *            the currentPage to set
         */
        public void setCurrentPage(Integer currentPage) {
            this.currentPage = currentPage;
            // 重新加载数据信息
            this.setParameters();
        }
    
        /**
         * @return the pageCount
         */
        public Integer getPageCount() {
            return pageCount;
        }
    
        /**
         * @param pageCount
         *            the pageCount to set
         */
        public void setPageCount(Integer pageCount) {
            this.pageCount = pageCount;
            // 重新加载数据信息
            this.setParameters();
        }
    
        /**
         * @return the pageMax
         */
        public Integer getPageMax() {
            return pageMax;
        }
    
        /**
         * @param pageMax
         *            the pageMax to set
         */
        public void setPageMax(Integer pageMax) {
            this.pageMax = pageMax;
        }
    
        /**
         * @return the list
         */
        public List<T> getList() {
            return list;
        }
    
        /**
         * @param list
         *            the list to set
         */
        public void setList(List<T> list) {
            this.list = list;
        }
    
        /**
         * @return the hasPrev
         */
        public Boolean getHasPrev() {
            return hasPrev;
        }
    
        /**
         * @param hasPrev
         *            the hasPrev to set
         */
        public void setHasPrev(Boolean hasPrev) {
            this.hasPrev = hasPrev;
        }
    
        /**
         * @return the hasNext
         */
        public Boolean getHasNext() {
            return hasNext;
        }
    
        /**
         * @param hasNext
         *            the hasNext to set
         */
        public void setHasNext(Boolean hasNext) {
            this.hasNext = hasNext;
        }
    
        /**
         * @return the dataCountMax
         */
        public Integer getDataCountMax() {
            return dataCountMax;
        }
    
        /**
         * @param dataCountMax
         *            the dataCountMax to set
         */
        public void setDataCountMax(Integer dataCountMax) {
            this.dataCountMax = dataCountMax;
        }
    
    }
    View Code

     可以实现多表查询

        public PageInfo findPageInfoBySql(String sql,String countsql, Integer currentPage, Integer pageCount) throws DAOException{
            Long count = (Long) entityManager.createQuery(countsql).getSingleResult();
            if (orderBy != null && !orderBy.isEmpty()) {
                sql+=" ORDER BY " + orderBy;
            }
            Query query = entityManager.createQuery(sql);    
            if (currentPage != null && pageCount != null) {
                query.setFirstResult((currentPage - 1) * pageCount);
                query.setMaxResults(pageCount);
            }
            return new PageInfo(currentPage, pageCount, count.intValue(),query.getResultList());
        }
    public class PageInfo implements Serializable {
        private static final Logger logger = Logger.getLogger(PageInfo.class);
    
        private static final long serialVersionUID = -4940465203107135908L;
        /** 当前页码 */
        private Integer currentPage;
        /** 每页数据行数 */
        private Integer pageCount;
        /** 数据总条数 */
        private Integer dataCountMax;
        /** 最大页码 */
        private Integer pageMax;
        /** 实体集合 */
        private List<?> list;
        /** 是否有上一页 */
        private Boolean hasPrev;
        /** 是否有下一页 */
        private Boolean hasNext;
    
        private List<?> listPaginDisplay = null;
    
        public List<?> getListPaginDisplay() {
            return listPaginDisplay;
        }
    
        public void setListPaginDisplay(List listPaginDisplay) {
            this.listPaginDisplay = listPaginDisplay;
        }
    
        public PageInfo() {
    
        }
    
        /**
         * @param currentPage
         *            当前页码
         * @param pageCount
         *            每页数据行数
         * @param dataCountMax
         *            数据总条数
         */
        public PageInfo(Integer currentPage, Integer pageCount, Integer dataCountMax) {
            this.currentPage = currentPage;
            this.pageCount = pageCount;
            this.dataCountMax = dataCountMax;
            this.setParameters();
        }
    
        /**
         * @param currentPage
         *            当前页码
         * @param pageCount
         *            每页数据行数
         * @param dataCountMax
         *            数据总条数
         * @param list
         *            分页后list
         */
        public PageInfo(Integer currentPage, Integer pageCount,
                Integer dataCountMax, List<?> list) {
            this.currentPage = currentPage;
            this.pageCount = pageCount;
            this.dataCountMax = dataCountMax;
            this.setParameters();
            this.list = list;
        }
    
        /** 重新加载数据信息 */
        public void setParameters() {
            if (currentPage == null) {
                currentPage = 1;
            }
            if (pageCount == null || pageCount < 1) {
                logger.warn("pageCount = 0, setPageCount=100");
                pageCount = 100;
            }
            if (dataCountMax == null) {
                dataCountMax = 10;
            }
    
            this.pageMax = dataCountMax % pageCount == 0 ? (dataCountMax / pageCount)
                    : (dataCountMax / pageCount + 1);
    
            if (currentPage > pageMax) {
                currentPage = pageMax;
            }
    
            this.hasPrev = currentPage > 1 ? true : false;
            this.hasNext = pageMax > currentPage ? true : false;
        }
    
        /**
         * @return the currentPage
         */
        public Integer getCurrentPage() {
            return currentPage;
        }
    
        /**
         * @param currentPage
         *            the currentPage to set
         */
        public void setCurrentPage(Integer currentPage) {
            this.currentPage = currentPage;
            // 重新加载数据信息
            this.setParameters();
        }
    
        /**
         * @return the pageCount
         */
        public Integer getPageCount() {
            return pageCount;
        }
    
        /**
         * @param pageCount
         *            the pageCount to set
         */
        public void setPageCount(Integer pageCount) {
            this.pageCount = pageCount;
            // 重新加载数据信息
            this.setParameters();
        }
    
        /**
         * @return the pageMax
         */
        public Integer getPageMax() {
            return pageMax;
        }
    
        /**
         * @param pageMax
         *            the pageMax to set
         */
        public void setPageMax(Integer pageMax) {
            this.pageMax = pageMax;
        }
    
        /**
         * @return the list
         */
        public List<?> getList() {
            return list;
        }
    
        /**
         * @param list
         *            the list to set
         */
        public void setList(List<?> list) {
            this.list = list;
        }
    
        /**
         * @return the hasPrev
         */
        public Boolean getHasPrev() {
            return hasPrev;
        }
    
        /**
         * @param hasPrev
         *            the hasPrev to set
         */
        public void setHasPrev(Boolean hasPrev) {
            this.hasPrev = hasPrev;
        }
    
        /**
         * @return the hasNext
         */
        public Boolean getHasNext() {
            return hasNext;
        }
    
        /**
         * @param hasNext
         *            the hasNext to set
         */
        public void setHasNext(Boolean hasNext) {
            this.hasNext = hasNext;
        }
    
        /**
         * @return the dataCountMax
         */
        public Integer getDataCountMax() {
            return dataCountMax;
        }
    
        /**
         * @param dataCountMax
         *            the dataCountMax to set
         */
        public void setDataCountMax(Integer dataCountMax) {
            this.dataCountMax = dataCountMax;
        }
    
    }
    View Code

      2、dao接口及实现:

    public interface PersonDao extends BaseDao<Person> {
        
    }
    public interface PersonDaoLocal extends PersonDao  {
        
    }
    public interface PersonDaoRemote extends PersonDao  {
        
    }
    @Stateless
    @Local(PersonDaoLocal.class)//dao层实现用本地接口
    public class PersonDaoImpl extends BaseDaoBean<Person> implements PersonDaoLocal,PersonDaoRemote{
        @Override
        @PersistenceContext(unitName = "UnitMySql")
        public void setEntityManager(EntityManager entityManager) {
            this.entityManager = entityManager;
        }
    
    }

      3、service接口及实现:

    public interface PersonService extends BaseService<Person> {
        public void update() throws ServiceException;
    }
    //无状态bean,本地接口和远程接口 jndi名称
    @Stateless
    @Local(PersonServiceLocal.class)
    @LocalBinding(jndiBinding = "PersonServiceBean/local")
    @Remote(PersonServiceRemote.class)
    @RemoteBinding(jndiBinding = "PersonServiceBean/remote")
    public class PersonServiceImpl implements PersonServiceLocal,PersonServiceRemote {        
        @EJB
        private PersonDaoLocal perosnDaoLocal;
    //通过ejb注入方式将dao层注入到service中
    }

       4、调用Service

    public class ActionSupportBase extends ActionSupport implements SessionAware, RequestAware, ServletResponseAware,
            ServletRequestAware, ApplicationAware {
    
        private static final long serialVersionUID = -4065551378754830182L;
        private static final Logger logger = Logger.getLogger(ActionSupportBase.class);
        protected static final String STATUS = "status";
        protected static final String MESSAGE = "message";
        protected static final String INFO = "info";
        protected static final String Y = "y";
        protected static final String N = "n";
        protected static final String MODIFY = "modify";
        protected static final String DETAIL = "detail";
        protected static final String SAVE_SUCCESS = "保存成功";
        protected static final String MODIFY_SUCCESS = "修改成功!";
        protected static final String DELETE_SUCCESS = "删除成功";
    
        protected String systemName = ServletActionContext.getServletContext().getInitParameter(ConstUtil.SYSTEMNAME);
        protected Map<String, Object> jsonMap = new HashMap<String, Object>();
        protected Map<String, Object> application;
        protected Map<String, Object> session;
        protected Map<String, Object> request;
    
        protected HttpServletResponse servletResponse;
        protected HttpServletRequest servletRequest;
    
        protected static Context context = null;
    
        public ActionSupportBase() {
            initContext();
        }
    
        protected void initContext() {
            try {
                if (context == null) {
                    context = new InitialContext();
                }
            } catch (NamingException e) {
                logger.warn(e);
            }
        }
    
        /**
         * 将一个字符串输出到浏览器
         * 
         * @author 李斌
         * @param json
         *            字符串
         */
        protected void writeJson(String json) {
            PrintWriter pw = null;
            try {
                servletResponse.setContentType("text/plain;charset=UTF-8");
                pw = servletResponse.getWriter();
                pw.write(json);
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (pw != null) {
                    pw.close();
                }
            }
        }
    
        public Map<String, Object> getApplication() {
            return application;
        }
    
        public void setApplication(Map<String, Object> application) {
            this.application = application;
        }
    
        public Map<String, Object> getSession() {
            return session;
        }
    
        public void setSession(Map<String, Object> session) {
            this.session = session;
        }
    
        public Map<String, Object> getRequest() {
            return request;
        }
    
        public void setRequest(Map<String, Object> request) {
            this.request = request;
        }
    
        public Map<String, Object> getJsonMap() {
            return jsonMap;
        }
    
        public void setJsonMap(Map<String, Object> jsonMap) {
            this.jsonMap = jsonMap;
        }
    
        public HttpServletResponse getServletResponse() {
            return servletResponse;
        }
    
        public void setServletResponse(HttpServletResponse servletResponse) {
            this.servletResponse = servletResponse;
        }
    
        public HttpServletRequest getServletRequest() {
            return servletRequest;
        }
    
        public void setServletRequest(HttpServletRequest servletRequest) {
            this.servletRequest = servletRequest;
        }
    
    }
    View Code
    Context context = new InitialContext();
    private PersonServiceRemote service = (PersonServiceRemote) context.lookup("PersonServiceBean/remote");

      三、创建web项目

        1、需要引入jboss的jboss-4.2.3.GAclient目录下的jar文件。

      2、在WEB-INF文件夹下创建jboss-web.xml文件,它用于设置发布到jboss上项目的根路径。

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE jboss-web
        PUBLIC "-//JBoss//DTD Web Application 2.3V2//EN"
        "http://www.jboss.org/j2ee/dtd/jboss-web_3_2.dtd">
    <jboss-web>
        <context-root>/</context-root>
        <virtual-host>self.net.cn</virtual-host>
    </jboss-web>

      3、如果要打包成ear项目,通过ant文件,在ear项目下需要创建一个META-INF文件夹,然后再META-INF文件夹下创建application.xml文件。

    <?xml version="1.0" encoding="ASCII"?>
    <application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" version="5">
      <display-name>my</display-name>
      <module>
        <ejb>myejb.jar</ejb>
      </module>
      <module>
        <web>
          <web-uri>myweb.war</web-uri>
          <context-root>/</context-root>
        </web>
      </module>
    </application>

    四、发布项目

        1、可以将项目打成war包或(ear)发布到jboss服务器上,可以发布到“ jboss-4.2.3.GAserveralldeploy ”目录下。

        2、访问资源文件:localhost:8080/项目名称/资源文件

        3、访问action:localhost:8080/项目名称/struts包命名空间/action

        4、http://127.0.0.1:8080/jbossws/services 查看webservice的发布情况

      5、127.0.0.1/jmx-console  查看jboss服务

  • 相关阅读:
    23种设计模式中的模板模式
    23种设计模式中的外观模式
    div,li,span自适应宽度换行问题
    监听自定义ItemRender的事件
    flex acionscript png图片去除多余空白,生成合适大小图片
    项目中用到RouteTable,发布到IIS7中无法访问
    记录Castle ActiveRecord访问Sqlite的配置
    如何卸载软件
    linux 下route命令
    linux 下 ifcfg-eth0 配置 以及ifconfig、ifup、ifdown区别
  • 原文地址:https://www.cnblogs.com/lbangel/p/3410987.html
Copyright © 2011-2022 走看看