首页 ┆ 网站地图 ┆ 在线留言 ┆ 游戏资讯 ┆ 资源下载 ┆ 端午节祝福 ┆ 迅雷在线影视 ┆淘宝手机在线充值 ┆淘宝游戏点卡充值 
设为首页
加入收藏
联系我们
高级搜索
您当前的位置: 主页>JAVA专区>STRUTS>Struts+hibernate实现投票系统代码实例
Struts+hibernate实现投票系统代码实例
来源: 发布时间:2008-04-01 发布人: 浏览: 人次   字体: [ ]  
package cn.hxex.vote.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;

import cn.hxex.vote.util.HibernateUtil;


/**
 * 用于进行Hibernate事务处理的Servlet过滤器
 *
 * 
@author galaxy
 
*/

public class HibernateFilter implements Filter {

    
private static Log log = LogFactory.getLog(HibernateFilter.class);

    
/**
     * 过滤器的主要方法
     * 用于实现Hibernate事务的开始和提交
     
*/

    
public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            
throws IOException, ServletException 
    
{
        
// 得到SessionFactory对象的实例
        SessionFactory sf = HibernateUtil.getSessionFactory();

        
try 
        
{
            
// 开始一个新的事务
            log.debug("Starting a database transaction");
            sf.getCurrentSession().beginTransaction();
            
            log.debug( 
"Request Path: " + ((HttpServletRequest)request).getServletPath() );
            
            
// 设置用户请求的编码格式
            request.setCharacterEncoding( "gb2312" );
            
            
// Call the next filter (continue request processing)
            chain.doFilter(request, response);

            
// 提交事务
            log.debug("Committing the database transaction");
            sf.getCurrentSession().getTransaction().commit();
            
        }
 
        
catch (Throwable ex) 
        
{
            ex.printStackTrace();
            
try 
            
{
                
// 会滚事务
                log.debug("Trying to rollback database transaction after exception");
                sf.getCurrentSession().getTransaction().rollback();
            }
 
            
catch (Throwable rbEx) 
            
{
                log.error(
"Could not rollback transaction after exception!", rbEx);
            }


            
// 抛出异常
            throw new ServletException(ex);
        }

    }


    
/**
     * Servlet过滤器的初始化方法
     * 可以读取配置文件中设置的配置参数
     
*/

    
public void init(FilterConfig filterConfig) throws ServletException {}

    
/**
     * Servlet的销毁方法
     * 用于释放过滤器所申请的资源
     
*/

    
public void destroy() {}

}
package cn.hxex.vote.util;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Interceptor;
import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;


/**
 * 基础的Hibernate辅助类,用于Hibernate的配置和启动。
 * <p>
 * 通过静态的初始化代码来读取Hibernate启动参数,并初始化
 * <tt>Configuration</tt>和<tt>SessionFactory</tt>对象。
 * <p>
 *
 * 
@author galaxy
 
*/

public class HibernateUtil 
{

    
private static Log log = LogFactory.getLog(HibernateUtil.class);

    
// 指定定义拦截器属性名
    private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class";

    
// 静态Configuration和SessionFactory对象的实例(全局唯一的)
    private static Configuration configuration;
    
private static SessionFactory sessionFactory;

    
static 
    
{
        
// 从缺省的配置文件创建SessionFactory
        try 
        
{
            
// 创建默认的Configuration对象的实例
            
// 如果你不使用JDK 5.0或者注释请使用new Configuration()
            
// 来创建Configuration()对象的实例
            configuration = new Configuration();

            
// 读取hibernate.properties或者hibernate.cfg.xml文件
            configuration.configure();

            
// 如果在配置文件中配置了拦截器,那么将其设置到configuration对象中
            String interceptorName = configuration.getProperty(INTERCEPTOR_CLASS);
            
if (interceptorName != null
            
{
                Class interceptorClass 
=
                        HibernateUtil.
class.getClassLoader().loadClass(interceptorName);
                Interceptor interceptor 
= (Interceptor)interceptorClass.newInstance();
                configuration.setInterceptor(interceptor);
            }


            
if (configuration.getProperty(Environment.SESSION_FACTORY_NAME) != null
            
{
                
// 让Hibernate将SessionFacory绑定到JNDI
                configuration.buildSessionFactory();
            }
 
            
else 
            
{
                
// 使用静态变量来保持SessioFactory对象的实例
                sessionFactory = configuration.buildSessionFactory();
            }


        }
 
        
catch (Throwable ex) 
        
{
            
// 输出异常信息
            log.error("Building SessionFactory failed.", ex);
            ex.printStackTrace();
            
throw new ExceptionInInitializerError(ex);
        }

    }


    
/**
     * 返回原始的Configuration对象的实例
     *
     * 
@return Configuration
     
*/

    
public static Configuration getConfiguration() 
    
{
        
return configuration;
    }


    
/**
     * 返回全局的SessionFactory对象的实例
     *
     * 
@return SessionFactory
     
*/

    
public static SessionFactory getSessionFactory() 
    
{
        SessionFactory sf 
= null;
        String sfName 
= configuration.getProperty(Environment.SESSION_FACTORY_NAME);
        
if ( sfName != null
        
{
            log.debug(
"Looking up SessionFactory in JNDI.");
            
try 
            
{
                sf 
= (SessionFactory) new InitialContext().lookup(sfName);
            }
 
            
catch (NamingException ex) 
            
{
                
throw new RuntimeException(ex);
            }

        }
 
        
else 
        
{
            sf 
= sessionFactory;
        }

        
if (sf == null)
            
throw new IllegalStateException( "SessionFactory not available." );
        
return sf;
    }


    
/**
     * 关闭当前的SessionFactory并且释放所有的资源
     
*/

    
public static void shutdown() 
    
{
        log.debug(
"Shutting down Hibernate.");
        
// Close caches and connection pools
        getSessionFactory().close();

        
// Clear static variables
        configuration = null;
        sessionFactory 
= null;
    }



    
/**
     * 使用静态的Configuration对象来重新构建SessionFactory。
     
*/

     
public static void rebuildSessionFactory() 
     
{
        log.debug(
"Using current Configuration for rebuild.");
        rebuildSessionFactory(configuration);
     }


    
/**
     * 使用指定的Configuration对象来重新构建SessionFactory对象。
     *
     * 
@param cfg
     
*/

     
public static void rebuildSessionFactory(Configuration cfg) 
     
{
        log.debug(
"Rebuilding the SessionFactory from given Configuration.");
        
synchronized(sessionFactory) 
        
{
            
if (sessionFactory != null && !sessionFactory.isClosed())
                sessionFactory.close();
            
if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null)
                cfg.buildSessionFactory();
            
else
                sessionFactory 
= cfg.buildSessionFactory();
            configuration 
= cfg;
        }

     }


    
/**
     * 在当前SessionFactory中注册一个拦截器
     
*/

    
public static SessionFactory registerInterceptorAndRebuild(Interceptor interceptor) 
    
{
        log.debug(
"Setting new global Hibernate interceptor and restarting.");
        configuration.setInterceptor(interceptor);
        rebuildSessionFactory();
        
return getSessionFactory();
    }


    
/**
     * 获得拦截器对象
     * 
     * 
@return Interceptor
     
*/

    
public static Interceptor getInterceptor() 
    
{
        
return configuration.getInterceptor();
    }


    
/**
     * 提交当前事务,并开始一个新的事务
     
*/

    
public static void commitAndBeginTransaction()
    
{
        sessionFactory.getCurrentSession().getTransaction().commit();
        sessionFactory.getCurrentSession().beginTransaction();
    }

}


 

package cn.hxex.vote.util;

import java.util.HashMap;
import java.util.Iterator;

public class SelectConst {
   
public static final HashMap votetypes;
   
public static final HashMap pictypes;
   
static{
       votetypes
=new HashMap();
       votetypes.put(
"checkbox""多选");
       votetypes.put(
"radio""单选");
       
       pictypes
=new HashMap();
       pictypes.put(
"PIE""饼图");
       pictypes.put(
"BAR""柱状图");
       pictypes.put(
"PIE3D""3D饼图");
       pictypes.put(
"BAR3D""3D柱状图");       
   }

   
   
public static String getVoteTypeOptions(String defaultValue){
       
return getOptions(votetypes,defaultValue);
   }

   
public static String getVoteTypeTitle(String key){

       
return (String)votetypes.get(key);
   }

   
public static String getPicTypeoptions(String defaultValue){
       
return getOptions(pictypes,defaultValue);
   }

   
public static String getPicTypeTitle(String key){
       
return (String)pictypes.get(key);
   }

   
public static String getOptions(HashMap options,String defaultValue){
       
       StringBuffer sf
=new StringBuffer();
       Iterator keys
=options.keySet().iterator();
       
while(keys.hasNext()){
           String key
=(String)keys.next();
           sf.append(
"<option value="");
           sf.append(key);
           
if(key.endsWith(defaultValue)){
              sf.append(
"" selected>");    
           }
else{
               sf.append(
"">");
           }

           sf.append(options.get(key));
           sf.append(
"</option>");
       }
 
       
       
return sf.toString();
   }

   
}

 
package cn.hxex.vote.util;

import java.util.Iterator;

import cn.hxex.vote.dao.IVoteDAO;
import cn.hxex.vote.model.Vote;
import cn.hxex.vote.model.Voteitems;