本系统采用Struts + Hibernate 作为主题框架数据库采用Mysql开源包使用JSTL+JFreeChart项目结构如下:action ChartServlet.java VoteAction.java VoteDeleteAction.java VoteEditAction.java VoteitemDeleteAction.java VoteitemEditAction.java VoteitemListAction.java VoteitemSaveAction.java VoteManageAction.java VoteSaveAction.javadao IVoteDAO.java VoteDAO.javasql script.sqlmodel vote.hbm.xml voteItem.hbm.xml Vote.java Voteitems.javautil DAOFactory.java HibernateDAO.java HibernateFilter.java HibernateUtil.java SelectConst.java VoteFunction.java
ChartServlet
package cn.hxex.vote.action; import java.io.IOException; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.model.Voteitems; import cn.hxex.vote.util.DAOFactory; public class ChartServlet extends HttpServlet ... { /** *//** * Constructor of the object. */ public ChartServlet() ...{ super(); } /** *//** * Destruction of the servlet. <br> */ public void destroy() ...{ super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{ doPost( request, response ); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{ String id=request.getParameter("id"); IVoteDAO votedao=DAOFactory.getVoteDAO(); Vote vote=votedao.getVote(id); JFreeChart chart=getChart(vote); response.setContentType("image/jpeg"); ChartUtilities.writeChartAsJPEG(response.getOutputStream(), 100, chart, 400,300); } public static JFreeChart getChart(Vote vote)...{ JFreeChart chart=null; if(vote.getPictype().indexOf("PIE")==0)...{ DefaultPieDataset date=new DefaultPieDataset(); Iterator iter=vote.getVoteitems().iterator(); while(iter.hasNext())...{ Voteitems vi=(Voteitems)iter.next(); date.setValue(vi.getTitle(), vi.getVotenum()); } if("PIE".equals(vote.getPictype()))...{ chart=ChartFactory.createPieChart(vote.getTitle(), date, false,false,false); }else...{ chart=ChartFactory.createPieChart3D(vote.getTitle(), date, false,false,false); } }else...{ DefaultCategoryDataset date=new DefaultCategoryDataset(); Iterator it=vote.getVoteitems().iterator(); while(it.hasNext())...{ Voteitems vi=(Voteitems)it.next(); date.addValue(vi.getVotenum(), "选项", vi.getTitle()); } if("BAR".equals(vote.getPictype()))...{ chart=ChartFactory.createBarChart(vote.getTitle(), "选项", "数量", date, PlotOrientation.VERTICAL, false,false,false); } else...{ chart=ChartFactory.createBarChart3D(vote.getTitle(), "选项", "数量", date, PlotOrientation.VERTICAL, false,false,false); } } return chart; } public void init() throws ServletException ...{ // Put your code here }} VoteAction /**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.model.Voteitems; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ String id=request.getParameter("id"); IVoteDAO voteDao=DAOFactory.getVoteDAO(); Vote vote=voteDao.getVote(id); String[] voteitem=request.getParameterValues(id); if(voteitem!=null&voteitem.length>0)...{ for(int i=0;i<voteitem.length;i++)...{ Iterator iter=vote.getVoteitems().iterator(); while(iter.hasNext())...{ Voteitems vi=(Voteitems)iter.next(); if(voteitem[i].equals(vi.getId()))...{ vi.increaseVotenum(); break; } } } } request.setAttribute("vote", vote); return mapping.findForward("success"); }}
VoteDeleteAction
/**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteDeleteAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); String id=request.getParameter("id"); Vote vote=voteDao.getVote(id); voteDao.deleteVote(vote); request.setAttribute("vote", vote); return mapping.findForward("success"); }}
/**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteEditAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); String id=request.getParameter("id"); Vote vote=voteDao.getVote(id); request.setAttribute("vote", vote); return mapping.findForward("success"); }} /**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.model.Voteitems; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteitemDeleteAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); String id=request.getParameter("id"); String voteid=voteDao.getVoteItem(id).getVote().getId(); Voteitems voteitem=voteDao.getVoteItem(id); voteDao.deleteVoteItem(voteitem); Vote vote=voteDao.getVote(voteid); vote.getVoteitems().remove(voteitem); request.setAttribute("vote", vote); return mapping.findForward("success"); }} /**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.model.Voteitems; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteitemEditAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); String id=request.getParameter("id"); Voteitems viforup = voteDao.getVoteItem( id ); request.setAttribute( "viforup", viforup ); Vote vote = viforup.getVote(); request.setAttribute( "vote", vote ); request.setAttribute("vote", vote); return mapping.findForward("success"); }} /**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteitemListAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); String id=request.getParameter("id"); Vote vote=voteDao.getVote(id); request.setAttribute("vote", vote); return mapping.findForward("success"); }} /**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model. * ; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteitemSaveAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); String voteid=request.getParameter("voteid"); String id=request.getParameter("id"); String title=request.getParameter("title"); String votenum=request.getParameter("votenum"); Voteitems voteitem=new Voteitems(); Vote vote=voteDao.getVote(voteid); if(id.equals("")||id==null)...{ voteitem.setTitle(title); voteitem.setVotenum(Integer.valueOf(votenum)); voteitem.setVote(vote); vote.getVoteitems().add(voteitem); voteDao.saveVoteItem(voteitem); }else...{ voteitem=voteDao.getVoteItem(id); voteitem.setTitle(title); voteitem.setVotenum(Integer.valueOf(votenum)); voteitem.setVote(vote); vote.getVoteitems().add(voteitem); voteDao.updateVoteItem(voteitem); } request.setAttribute("vote", vote); //request.setAttribute("viforup", voteitem); return mapping.findForward("success"); }} /**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-10-2007 * * XDoclet definition: * @struts.action validate="true" */ public class VoteManageAction extends Action ... { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); List votes=voteDao.getAllVotes(); request.setAttribute("votes", votes); return mapping.findForward("success"); }} /**/ /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package cn.hxex.vote.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.hxex.vote.dao.IVoteDAO; import cn.hxex.vote.model.Vote; import cn.hxex.vote.util.DAOFactory; /** */ /** * MyEclipse Struts * Creation date: 02-11-2007 * * XDoclet definition: * @struts.action validate="true" * @struts.action-forward name="success" path="123" */ public class VoteSaveAction extends Action ... { /**//* * Generated Methods */ /** *//** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ IVoteDAO voteDao=DAOFactory.getVoteDAO(); String id=request.getParameter("id"); String name=request.getParameter("name"); String title=request.getParameter("title"); String votetype=request.getParameter("votetype"); String pictype=request.getParameter("pictype"); Vote vote=new Vote(); if(id.equals("")||id==null)...{ vote.setId(id); vote.setName(name); vote.setTitle(title); vote.setVotetype(votetype); vote.setPictype(pictype); voteDao.saveVote(vote); } else ...{ vote=voteDao.getVote(id); vote.setName(name); vote.setTitle(title); vote.setVotetype(votetype); vote.setPictype(pictype); voteDao.updateVote(vote); } request.setAttribute("vote", vote); return mapping.findForward("success"); }} package cn.hxex.vote.dao; import java.util.List; import cn.hxex.vote.model.Vote; import cn.hxex.vote.model.Voteitems; public interface IVoteDAO ... { public void saveVote(Vote vote); public void saveVoteItem(Voteitems voteitem); public void updateVote(Vote vote); public void updateVoteItem(Voteitems voteitem); public void deleteVote(Vote vote); public void deleteVoteItem(Voteitems voteitem); public Vote getVote(String id); public Vote getVoteByName(String name); public List getAllVotes(); public Voteitems getVoteItem(String id);} package cn.hxex.vote.dao; import java.util.List; import cn.hxex.vote.model.Vote; import cn.hxex.vote.model.Voteitems; import cn.hxex.vote.util.HibernateDAO; public class VoteDAO extends HibernateDAO implements IVoteDAO ... { public void deleteVote(Vote vote) ...{ super.deleteObject(vote); } public void deleteVoteItem(Voteitems voteitem) ...{ super.deleteObject(voteitem); } public List getAllVotes() ...{ String hql="from Vote"; return super.getObjects(hql); } public Vote getVote(String id) ...{ return (Vote)super.getObject(Vote.class, id); } public Vote getVoteByName(String name) ...{ String hql="from Vote where name='"+name+"'"; return (Vote)super.getObject(hql); } public Voteitems getVoteItem(String id) ...{ return (Voteitems)super.getObject(Voteitems.class, id); } public void saveVote(Vote vote) ...{ super.saveObject(vote); } public void saveVoteItem(Voteitems voteitem) ...{ super.saveObject(voteitem); } public void updateVote(Vote vote) ...{ super.updateObject(vote); } public void updateVoteItem(Voteitems voteitem) ...{ super.updateObject(voteitem); }} <? xml version="1.0" ?> <! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > < hibernate-mapping package ="cn.hxex.vote.model" > < class name ="Vote" table ="vote" > < id name ="id" column ="id" type ="string" > < generator class ="uuid.hex" ></ generator > </ id > < property name ="name" column ="name" > </ property > < property name ="title" column ="title" > </ property > < property name ="votetype" column ="votetype" > </ property > < property name ="pictype" column ="pictype" > </ property > < set name ="voteitems" cascade ="delete" order-by ="title asc" inverse ="true" > < key column ="vote_id" ></ key > < one-to-many class ="Voteitems" /> </ set > </ class > </ hibernate-mapping > <? xml version="1.0" ?> <! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > < hibernate-mapping package ="cn.hxex.vote.model" > < class name ="Voteitems" table ="voteitem" > < id name ="id" column ="id" type ="string" > < generator class ="uuid.hex" ></ generator > </ id > < property name ="title" column ="title" > </ property > < property name ="votenum" column ="votenum" > </ property > < many-to-one name ="vote" column ="vote_id" ></ many-to-one > </ class > </ hibernate-mapping > package cn.hxex.vote.model; import java.util.Set; public class Vote ... { private String id; private String name; private String title; private String votetype; private String pictype; private Set voteitems;public String getId() ...{ return id;}public void setId(String id) ...{ this.id = id;}public String getName() ...{ return name;}public void setName(String name) ...{ this.name = name;}public String getPictype() ...{ return pictype;}public void setPictype(String pictype) ...{ this.pictype = pictype;}public String getTitle() ...{ return title;}public void setTitle(String title) ...{ this.title = title;}public Set getVoteitems() ...{ return voteitems;}public void setVoteitems(Set voteitems) ...{ this.voteitems = voteitems;}public String getVotetype() ...{ return votetype;}public void setVotetype(String votetype) ...{ this.votetype = votetype;}} package cn.hxex.vote.model; public class Voteitems ... { private String id; private String title; private Integer votenum; private Vote vote;public String getId() ...{ return id;}public void setId(String id) ...{ this.id = id;}public String getTitle() ...{ return title;}public void setTitle(String title) ...{ this.title = title;}public Vote getVote() ...{ return vote;}public void setVote(Vote vote) ...{ this.vote = vote;}public Integer getVotenum() ...{ return votenum;}public void setVotenum(Integer votenum) ...{ this.votenum = votenum;}public void increaseVotenum()...{ int num=getVotenum().intValue()+1; setVotenum(new Integer(num));}} CREATE TABLE `vote` ( `id` varchar ( 50 ) NOT NULL default '' , `name` varchar ( 50 ) default NULL , `title` varchar ( 50 ) default NULL , `votetype` varchar ( 50 ) default NULL , `pictype` varchar ( 50 ) default NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB DEFAULT CHARSET = gb2312 ROW_FORMAT = REDUNDANT; CREATE TABLE `voteitem` ( `id` varchar ( 50 ) NOT NULL default '' , `title` varchar ( 50 ) default NULL , `votenum` varchar ( 50 ) default NULL , `vote_id` varchar ( 50 ) NOT NULL , PRIMARY KEY (`id`), KEY `fk_vote_no` (`vote_id`),) ENGINE = InnoDB DEFAULT CHARSET = gb2312 ROW_FORMAT = REDUNDANT; package cn.hxex.vote.util; import cn.hxex.vote.dao.IVoteDAO; public class DAOFactory ... { public static IVoteDAO getVoteDAO()...{ return (IVoteDAO)getInstance("cn.hxex.vote.dao.VoteDAO"); } static Object getInstance(String className)...{ try ...{ Class cls=Class.forName(className); return cls.newInstance(); } catch (Exception e) ...{ e.printStackTrace(); return null; } }} package cn.hxex.vote.util; import java.util.List; import org.hibernate.Session; public class HibernateDAO ... { public void saveObject(Object obj)...{ getSession().save(obj); } public void updateObject(Object obj)...{ getSession().update(obj); } public List getObjects(String hql)...{ List result=getSession().createQuery(hql).list(); return result; } public Object getObject(String hql)...{ Object result=getSession().createQuery(hql).uniqueResult(); return result; } public Object getObject(Class cls,String id)...{ return getSession().get(cls, id); } public void deleteObject(Object obj)...{ getSession().delete(obj); } protected Session getSession()...{ return HibernateUtil.getSessionFactory().getCurrentSession(); }} 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; public class VoteFunction ... { public static String votetype(String votetype)...{ return SelectConst.getVoteTypeTitle(votetype); } public static String votetypeoptions(String defaultValue)...{ return SelectConst.getVoteTypeOptions(defaultValue); } public static String pictype(String pictype)...{ return SelectConst.getPicTypeTitle(pictype); } public static String pictypeoptions(String defaultValue)...{ return SelectConst.getPicTypeoptions(defaultValue); } public static String display(String votename)...{ StringBuffer buf=new StringBuffer(); buf.append("<table>"); buf.append("<form method="post" action="/VoteManager/vote.do">"); IVoteDAO voteDao=DAOFactory.getVoteDAO(); Vote vote=voteDao.getVoteByName(votename); if(vote!=null)...{ buf.append(line("<b>"+vote.getTitle()+"</b>")); Iterator iter=vote.getVoteitems().iterator(); int i=0; while(iter.hasNext())...{ Voteitems vi=(Voteitems)iter.next(); String control="<input type="" +vote.getVotetype() +"" name="" +vote.getId()+"" value="" +vi.getId()+"">"; buf.append(line(++i+"."+control+vi.getTitle())); } } buf.append("<tr><td align="center">"); buf.append("<input type="submit" value="投票">"); buf.append("  "); buf.append("<input type="reset" value="重置">"); buf.append("<input type="hidden" name="id" value=""+vote.getId()+"">"); buf.append("</td></tr>"); buf.append("</form>"); buf.append("</table>"); return buf.toString(); } public static String line(String line)...{ return "<tr><td>"+line+"</td></tr>"; }}
<? xml version='1.0' encoding='UTF-8' ?> <! DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" > <!-- Generated by MyEclipse Hibernate Tools. --> < hibernate-configuration > < session-factory > < property name ="myeclipse.connection.profile" > mysql </ property > < property name ="connection.url" > jdbc:mysql://localhost:3306/votemanager </ property > < property name ="connection.username" > root </ property > < property name ="connection.password" > 1234 </ property > < property name ="connection.driver_class" > com.mysql.jdbc.Driver </ property > < property name ="dialect" > org.hibernate.dialect.MySQLDialect </ property > < property name ="current_session_context_class" > thread </ property > < mapping resource ="cn/hxex/vote/model/vote.hbm.xml" /> < mapping resource ="cn/hxex/vote/model/voteItem.hbm.xml" /> </ session-factory > </ hibernate-configuration >
index.jsp
<% ... @page contentType="text/html;charset=gb2312" %> <% ... @ taglib prefix="vote" uri="http://hxex.cn/vote" %> < html > < head > < title > 投票系统 </ title > </ head > < body > < center > < table > < tr > < td > < img src ="img/index.gif" width ="150" > </ td > < td > < h1 > 请您投票 </ h1 > ${vote:display('salary')} </ td > </ tr > </ table > </ center > </ body > </ html >
vote_add_update.jsp
<% ... @page contentType="text/html;charset=gb2312" %> <% ... @ taglib prefix="vote" uri="http://hxex.cn/vote" %> < html > < head > <% ... String context=request.getContextPath(); %> < meta http-equiv ="content-type" content ="text/html;charset=gb2312" > < title > 发布投票 </ title > < script type ="text/javascript" src ="js/common.js" ></ script > < script type ="text/javascript" > ... function checkValid(form)...{ var checks=[[form.name,"请输入投票标识"],[form.text,"请输入投票名称"]]; if(!isRequired(checks))...{ return false; } return true; } function gomanager()...{ window.location.href="<%=context%>/voteManage.do" } </ script > </ head > < center > < h1 > 发布投票 </ h1 > < p > < table > < form method ="post" name ="main" action ="<%=context%>/voteSave.do" onsubmit ="return checkValid(this);" > < tr > < td width ="100" > 投票名称 </ td > < td >< input type ="text" name ="name" value ="${vote.name}" > * </ td > </ tr > < tr > < td > 投票标识 </ td > < td >< input type ="text" name ="title" value ="${vote.title}" > * </ td > </ tr > < tr > < td > 投票类型 </ td > < td > < select name ="votetype" > ${vote:votetypeoptions(vote.votetype) } </ select > </ td > </ tr > < tr > < td > 图形类型 </ td > < td > < select name ="pictype" > ${vote:pictypeoptions(vote.pictype) } </ select > </ td > </ tr > < tr > < td colspan ="2" align ="center" > < input type ="hidden" name ="id" value ="${vote.id }" > < input type ="submit" value ="保存" > < input type ="reset" value ="重填" > < input type ="button" value ="返回" onclick ="gomanager();" > </ td > </ tr > </ form > </ table > < p > < img src ="img/voteadd.gif" width ="200" > </ center > </ html >
vote_list.jsp
<% ... @ taglib uri="/WEB-INF/c.tld" prefix="c" %> <% ... @ taglib uri="http://hxex.cn/vote" prefix="vote" %> <% ... @page contentType="text/html;charset=gb2312" %> < html > < head > <% ... String context=request.getContextPath(); %> < title > 投票管理系统 </ title > </ head > < body > < center > < h1 > 投票管理系统 </ h1 > < table border ="1" > < tr > < td colspan ="5" >< font color ="red" > ${msg} </ font ></ td > </ tr > < tr > < td align ="center" > 投票标识 </ td > < td align ="center" > 投票名称 </ td > < td align ="center" > 投票类型 </ td > < td align ="center" > 图形类型 </ td > < td align ="center" > 操作类型 </ td > </ tr > < c:forEach var ="vote" items ="${votes}" > < tr > < td > ${vote.name} </ td > < td > ${vote.title} </ td > < td > ${vote:votetype(vote.votetype)} </ td > < td > ${vote:pictype(vote.pictype)} </ td > < td align ="center" > < a href ="<%=context %>/voteEdit.do?id=${vote.id}" > 修改投票 </ a > < a href ="<%=context %>/voteDelete.do?id=${vote.id}" > 删除投票 </ a > < a href ="<%=context %>/voteitemList.do?id=${vote.id}" > 修改选项 </ a > </ td > </ tr > </ c:forEach > </ table > < p > < a href ="vote_add_update.jsp" > 发布投票 </ a > < p > < img src ="img/manager.gif" width ="300" > </ center > </ body > </ html >
vote_result.jsp
<% ... @page contentType="text/html;charset=gb2312" %> <% ... @ taglib prefix="vote" uri="http://hxex.cn/vote" %> <% ... @ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> < html > < head > < title > 投票结果 </ title > </ head > < body > < center > < h1 > ${vote.title} </ h1 > < h3 > 投票结果 </ h3 > < img src ="/VoteManager/chart?id=${vote.id}" > < table width ="300" border ="1" > < tr > < td align ="center" > 选项 </ td > < td align ="center" > 结果 </ td > </ tr > < c:forEach var ="voteitem" items ="${vote.voteitems}" > < tr > < td > ${voteitem.title} </ td > < td > ${voteitem.votenum} </ td > </ tr > </ c:forEach > < tr > < td colspan ="2" align ="center" > < a href ="index.jsp" > 返回 </ a > </ td > </ tr > </ table > </ center > </ body > </ html > voteitem_add_update.jsp <% ... @ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% ... @ taglib prefix="vote" uri="http://hxex.cn/vote" %> <% ... @page contentType="text/html;charset=gb2312" %> <% ... @page isELIgnored="false" %> < html > < head > <% ... String context=request.getContextPath(); %> < script type ="text/javascript" src ="js/common.js" ></ script > < script type ="text/javascript" > ... function checkValid(form)...{ var checks=[[form.title,"请输入投票选项"],[form.votenum,"请输入票数"]]; if(isRequired(checks))...{ return true; } return false; } function gomanager()...{ window.location.href="<%=context%>/voteManage.do" } </ script > < title > 维护投票条目 </ title > </ head > < body > < center > < h1 > 维护投票条目 </ h1 > < table > < tr > < td >< font color ="red" > ${msg} </ font ></ td > < td valign ="bottom" rowspan ="13" > < img src ="img/voteitem.gif" width ="150" > </ td > </ tr > < tr > < td > </ td > </ tr > < tr > < td align ="center" > 投票信息 </ td > </ tr > < tr > < td > 投票标识:${vote.name } </ td > </ tr > < tr > < td > 投票名称:${vote.title } </ td > </ tr > < tr > < td > 投票类型:${vote:votetype(vote.votetype) } </ td > </ tr > < tr > < td > 图形类型:${vote:pictype(vote.pictype) } </ td > </ tr > < tr > < td > </ td > </ tr > < c:if test ="${!empty vote.voteitems}" > < tr > < td align ="center" > 已经存在的投票选项 </ td > </ tr > < tr > < td > < table width ="100%" border ="1" > < tr > < td align ="center" > 选项 </ td > < td align ="center" > 票数 </ td > < td align ="center" > 操作 </ td > </ tr > < c:forEach var ="voteitem" items ="${vote.voteitems}" > < tr > < td > ${voteitem.title} </ td > < td > ${voteitem.votenum} </ td > < td align ="center" > < a href ="<%=context %>/voteitemEdit.do?id=${voteitem.id}" > 修改选项 </ a > < a href ="<%=context %>/voteitemDelete.do?id=${voteitem.id}&voteid=${vote.id}" > 删除选项 </ a > </ td > </ tr > </ c:forEach > </ table > </ td > </ tr > < tr > < td > </ td > </ tr > </ c:if > < tr > < td > 请输入投票选项的信息: </ td > </ tr > < tr > < td > < table width ="100%" > < form method ="post" action ="<%=context %>/voteitemSave.do" onsubmit ="return checkValid( this );" > < tr > < td > 选项: </ td > < td >< input type ="text" name ="title" value ="${viforup.title}" > * </ td > </ tr > < tr > < td > 票数: </ td > < td >< input type ="text" name ="votenum" value ="${viforup.votenum}" ></ td > </ tr > < tr > < td colspan ="2" align ="center" > < input type ="hidden" name ="voteid" value ="${vote.id }" > < input type ="hidden" name ="id" value ="${viforup.id}" > < input type ="submit" value ="提交" > < input type ="reset" value ="重填" > < input type ="button" value ="返回" onclick ="gomanager();" > </ td > </ tr > </ form > </ table > </ td > </ tr > </ table > </ center > </ body > </ html > common.js function isRequired( checked ) ... { for( var i=0; i<checked.length; i++ ) ...{ var input = checked[i][0]; if( input.value==null || input.value.length==0 ) ...{ alert( checked[i][1] ); input.focus(); return false; } } return true;} struts-config.xml <? xml version="1.0" encoding="UTF-8" ?> <! DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd" > < struts-config > < data-sources /> < form-beans /> < global-exceptions /> < global-forwards > </ global-forwards > < action-mappings > < action path ="/voteManage" type ="cn.hxex.vote.action.VoteManageAction" > < forward name ="success" path ="/vote_list.jsp" /> </ action > < action path ="/voteSave" type ="cn.hxex.vote.action.VoteSaveAction" > < forward name ="success" path ="/voteitem_add_update.jsp" /> </ action > < action path ="/voteEdit" type ="cn.hxex.vote.action.VoteEditAction" > < forward name ="success" path ="/vote_add_update.jsp" /> </ action > < action path ="/voteDelete" type ="cn.hxex.vote.action.VoteDeleteAction" > < forward name ="success" path ="/voteManage.do" /> </ action > < action path ="/voteitemSave" type ="cn.hxex.vote.action.VoteitemSaveAction" > < forward name ="success" path ="/voteitem_add_update.jsp" /> </ action > < action path ="/voteitemDelete" type ="cn.hxex.vote.action.VoteitemDeleteAction" > < forward name ="success" path ="/voteitem_add_update.jsp" /> </ action > < action path ="/voteitemList" type ="cn.hxex.vote.action.VoteitemListAction" > < forward name ="success" path ="/voteitem_add_update.jsp" /> </ action > < action path ="/voteitemEdit" type ="cn.hxex.vote.action.VoteitemEditAction" > < forward name ="success" path ="/voteitem_add_update.jsp" /> </ action > < action path ="/vote" type ="cn.hxex.vote.action.VoteAction" > < forward name ="success" path ="/vote_result.jsp" /> </ action > </ action-mappings > < message-resources parameter ="ApplicationResources" /> </ struts-config > web.xml <? xml version="1.0" encoding="UTF-8" ?> < web-app xmlns ="http://java.sun.com/xml/ns/j2ee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" version ="2.4" xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" > < filter > < filter-name > HibernateFilter </ filter-name > < filter-class > cn.hxex.vote.util.HibernateFilter </ filter-class > </ filter > < filter-mapping > < filter-name > HibernateFilter </ filter-name > < url-pattern > /* </ url-pattern > </ filter-mapping > < servlet > < servlet-name > action </ servlet-name > < servlet-class > org.apache.struts.action.ActionServlet </ servlet-class > < init-param > < param-name > config </ param-name > < param-value > /WEB-INF/struts-config.xml </ param-value > </ init-param > < init-param > < param-name > debug </ param-name > < param-value > 3 </ param-value > </ init-param > < init-param > < param-name > detail </ param-name > < param-value > 3 </ param-value > </ init-param > < load-on-startup > 0 </ load-on-startup > </ servlet > < servlet-mapping > < servlet-name > action </ servlet-name > < url-pattern > *.do </ url-pattern > </ servlet-mapping > < servlet > < servlet-name > Chart </ servlet-name > < servlet-class > cn.hxex.vote.action.ChartServlet </ servlet-class > </ servlet > < servlet-mapping > < servlet-name > Chart </ servlet-name > < url-pattern > /chart </ url-pattern > </ servlet-mapping > < jsp-config > < taglib > < taglib-uri > http://hxex.cn/vote </ taglib-uri > < taglib-location > /WEB-INF/vote.tld </ taglib-location > </ taglib > </ jsp-config > </ web-app > vote.tld <? xml version="1.0" encoding="UTF-8" ?> < taglib xmlns ="http://java.sun.com/xml/ns/j2ee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version ="2.0" > < description > vote function library </ description > < display-name > Vote </ display-name > < tlib-version > 1.0 </ tlib-version > < short-name > vote </ short-name > < uri > http://hxex.cn/vote </ uri > < function > < name > votetype </ name > < function-class > cn.hxex.vote.util.VoteFunction </ function-class > < function-signature > java.lang.String votetype(java.lang.String) </ function-signature > </ function > < function > < name > pictype </ name > < function-class > cn.hxex.vote.util.VoteFunction </ function-class > < function-signature > java.lang.String pictype(java.lang.String) </ function-signature > </ function > < function > < name > votetypeoptions </ name > < function-class > cn.hxex.vote.util.VoteFunction </ function-class > < function-signature > java.lang.String votetypeoptions(java.lang.String) </ function-signature > </ function > < function > < name > pictypeoptions </ name > < function-class > cn.hxex.vote.util.VoteFunction </ function-class > < function-signature > java.lang.String pictypeoptions(java.lang.String) </ function-signature > </ function > < function > < name > display </ name > < function-class > cn.hxex.vote.util.VoteFunction </ function-class > < function-signature > java.lang.String display(java.lang.String) </ function-signature > </ function > </ taglib >