基于spring+dwr+xml无刷新投票(调查)系统

Posted on 2007-11-19 18:04 flustar 阅读(1358) 评论(0)  编辑  收藏 所属分类: SpringJavascriptXML

一、建立xml的数据结构,文件名为:vote.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<votes voteTotalCount="0">

    <vote voteId="1" name="c语言 " voteCount="0" percentum="0" />

    <vote voteId="2" name="c++" voteCount="0" percentum="0" />

    <vote voteId="3" name="java" voteCount="0" percentum="0" />

    <vote voteId="4" name="汇编语言" voteCount="0" percentum="0" />

 </votes>

在你的web应用的根目录建立xml文件夹,将其拷贝到该目录下。

二、建立xml对应的bean

/**

 * @author flustar

 * @version 创建时间:Jul 11, 2007 5:17:53 PM

 * 类说明

 */

……………………………………………………………………….

……………………………………………………………………….

public class VoteBean {

    private String voteId;

   private String name;

    private String voteCount;

    private String voteTotalCount;

    private String percentum;

    public VoteBean() {

      

    }

    public String getPercentum() {

       return percentum;

    }

    public void setPercentum(String percentum) {

       this.percentum = percentum;

    }

    public String getVoteId() {

       return voteId;

    }

 

    public void setVoteId(String voteId) {

       this.voteId = voteId;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public String getVoteCount() {

       return voteCount;

    }

 

    public void setVoteCount(String voteCount) {

       this.voteCount = voteCount;

    }

}

三、建立处理具体逻辑的service

package com.flustar.service;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.text.NumberFormat;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import org.jdom.Attribute;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.input.SAXBuilder;

import org.jdom.output.Format;

import org.jdom.output.XMLOutputter;

import org.jdom.xpath.XPath;

import com.flustar.web.beans.VoteBean;

import com.flustar.web.config.ContextConfig;

public class VoteService {

       private Element root, vote;

       private Document doc;

      private Attribute voteTotalCount;

       private VoteBean voteBean;

       private List<VoteBean> voteBeanList;

       private String path = ContextConfig.getContextPath()

                     + "/xml/vote.xml";

       public void buildDoc() throws Exception {

              FileInputStream fi = null;

              fi = new FileInputStream(path);

              SAXBuilder sb = new SAXBuilder();

              doc = sb.build(fi);

       }

       public void formatDoc() throws Exception {

              Format format = Format.getCompactFormat();

              format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8

              format.setIndent("    ");// 设置xml文件缩进为4个空格

              XMLOutputter xmlOut = new XMLOutputter(format);

              xmlOut.output(doc, new FileOutputStream(path));

       }

 

       public String floatToPercentum(Double doubleNum) {

              NumberFormat numberFormat = NumberFormat.getPercentInstance();

              numberFormat.setMinimumFractionDigits(2);

              // numberFormat.setMaximumIntegerDigits(2);

              String str = numberFormat.format(doubleNum);

              //System.out.println(str);

              return str;

       }

 

       public void updateVoteCount(String voteId) throws Exception {

              buildDoc();

              root = doc.getRootElement();

              vote = (Element) XPath.selectSingleNode(root, "//vote[@voteId='"

                            + voteId + "']");

              int voteCount = Integer.parseInt(vote.getAttributeValue("voteCount")) + 1;

              //System.out.println(voteCount);

              vote.setAttribute("voteCount", String.valueOf(voteCount));

              int totalCount = Integer.parseInt(root

                            .getAttributeValue("voteTotalCount")) + 1;

              voteTotalCount = new Attribute("voteTotalCount", String

                            .valueOf(totalCount));

              root.setAttribute(voteTotalCount);

              System.out.println(totalCount);

              formatDoc();

              updateAllVoteCount();//更新所有的百分比

 

       }

    public void updateAllVoteCount()throws Exception{

           buildDoc();

           root=doc.getRootElement();

           int totalCount = Integer.parseInt(root

                            .getAttributeValue("voteTotalCount"));

           List voteList=XPath.selectNodes(root,"/votes/vote");

           for(int i=0;i<voteList.size();i++){

                  vote=(Element)voteList.get(i);

                  int voteCount = Integer.parseInt(vote.getAttributeValue("voteCount"));

                  System.out.println(voteCount);

                  vote.setAttribute("voteCount", String.valueOf(voteCount));

                  vote.setAttribute("percentum", floatToPercentum(1.0 * voteCount

                                / totalCount));

           }

           formatDoc();

    }

       public List getAllVote() throws Exception {

              buildDoc();

              voteBeanList = new ArrayList();

              root = doc.getRootElement();

              String totalCount = root.getAttributeValue("voteTotalCount");

              List voteList = root.getChildren();

              Iterator i = voteList.iterator();

 

              while (i.hasNext()) {

                     voteBean = new VoteBean();

                     voteBean.setVoteTotalCount(totalCount);

                     vote = (Element) i.next();

                     String name = vote.getAttributeValue("name");

                     String voteCount = vote.getAttributeValue("voteCount");

                     String percentum = vote.getAttributeValue("percentum");

 

                     voteBean.setName(name);

                     voteBean.setVoteCount(voteCount);

                     voteBean.setPercentum(percentum);

                     voteBeanList.add(voteBean);

              }

              return voteBeanList;

       }

 

}

 

    public String getVoteTotalCount() {

       return voteTotalCount;

    }

 

    public void setVoteTotalCount(String voteTotalCount) {

       this.voteTotalCount = voteTotalCount;

    }

}

 

四、获取上下文路径的listener

package com.flustar.web.listener;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import com.flustar.web.config.ContextConfig;

public class ConfigLoadContextListener implements  ServletContextListener{

    public void contextDestroyed(ServletContextEvent arg0) {

       // TODO Auto-generated method stub

           }

    public void contextInitialized(ServletContextEvent contextEvent) {

       // TODO Auto-generated method stub

              String contextPath = contextEvent.getServletContext().getRealPath("/");

       ContextConfig.setContextPath(contextPath);

           }

}

………………………………………………………..

……………………………………………………………

 

public class ContextConfig {

    private static String contextPath;

 

    public static String getContextPath() {

       return contextPath;

    }

 

    public static void setContextPath(String contextPath) {

       ContextConfig.contextPath = contextPath;

    }

……………………………………………………………………

………………………………………………………………..

}

五、在applicationContext-service.xml中注册VoteService

<bean name="voteService" class="com.flustar.service.imp.VoteService"/>

六、注册xml,在你的web应用的WEB-INFO目录下建立applicationContext-dwr.xml文件,内容为:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd">

<dwr>

    <allow>

      <create  creator="spring" javascript="VoteService" >

         <param name="beanName" value="voteService"></param>

         <include method="updateVoteCount"/>

         <include method="getAllVote"/>

      </create>

      <convert converter="bean"  match="com.flustar.web.beans.VoteBean" />

           </allow>

</dwr>

 

七、修改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"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

    version="2.4">

    …………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………………..

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>

…………………………………..

       /WEB-INF/classes/applicationContext-service.xml

</param-value>

    </context-param>

 …………………………………………………………………………………………………………………………………………….     <listener-class>com.flustar.web.listener.ConfigLoadContextListener</listener-class>

    …………………………………………………………………………………………………………………………………………….   

  <servlet>

    <servlet-name>dwr-invoker</servlet-name>

    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>

    <init-param>

      <param-name>debug</param-name>

      <param-value>true</param-value>

    </init-param>

  </servlet>

 

  <servlet-mapping>

    <servlet-name>dwr-invoker</servlet-name>

    <url-pattern>/dwr/*</url-pattern>

  </servlet-mapping> 

…………………………………………………………………………………………………………………………………………….   

</web-app>

八、jsp页面

1)

<%@ page contentType="text/html; charset=gbk" language="java" import="java.sql.*" errorPage="" %>

<html>

<head>

<title>投票系统</title>

       <script type='text/javascript' src='dwr/engine.js'> </script>

        <script type='text/javascript' src='dwr/util.js'> </script>

        <script type='text/javascript' src='dwr/interface/VoteService.js'> </script>

       <script type='text/javascript'>

function vote(){

       

     var   obj=document.getElementsByName('radio'); 

    

         if   (obj!=null){ 

         var j=0;

           for   (var   i=0;i<obj.length;i++){ 

             if   (obj[i].checked)  

              {  

               

                   VoteService.updateVoteCount(obj[i].value);

                   alert("投票成功!");

                  obj[i].checked=false;

                  break;

               }

              }

               j=j+1;

             

          }

         if(j==obj.length){

                alert("请选中其中的一项,再投票!");

               }

          

      }

   

    }

  function showwin(){

    window.open('voteresult.htm','voteresult','height=400, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');

   }

 }

</script>

</head>

<body>

<div >

    <h1 >

       你使用最多的一门语言是?

    </h1>

</div>

<div>

<div>

        <span>     <h1><input type="radio" name="radio" id="radio" value="1" />

       C语言</h1>

        </span>

       <span> <h1 ><input type="radio" name="radio" id="radio" value="2" />c++ </h1> </span>

       <span ><h1 ><input type="radio" name="radio" id="radio" value="3" />java </h1> </span>

       <span><h1 ><input type="radio" name="radio" id="radio" value="4"/>汇编语言</h1> </span>

</div>

</div>

<div id="toupiao"><input class="btn" type="button" value="投票" onClick="vote()" /><input class="btn" type="button" value="查看" onClick="showwin()"/></div>

</body>

</html>

2)

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=gb2312">

<title>投票结果</title>

       <script type='text/javascript' src='dwr/engine.js'> </script>

        <script type='text/javascript' src='dwr/util.js'> </script>

        <script type='text/javascript' src='dwr/interface/VoteService.js'> </script>

        <script type='text/javascript' >

function showresult(){

             VoteService.getAllVote(function(data){

             document.getElementById("totalCount").innerHTML=data[0].voteTotalCount;

             for(var i=0;i<data.length;i++){

                  var voteBean=data[i];

                  document.getElementById("xuanshou"+i).innerHTML=voteBean.name;

                  document.getElementById("baifenbi"+i).innerHTML=voteBean.percentum;

                  document.getElementById("piaoshu"+i).innerHTML=voteBean.voteCount;

                  document.getElementById("img"+i).width=voteBean.voteCount/data[0].voteTotalCount*310;

                                   

      }

    });

          

}

</script>

</head>

<body onLoad="showresult()">

<div id="voteRs">

<table border="0" cellpadding="0" cellspacing="0">

  <CAPTION valign="top" class="subject">

投票结果

    </CAPTION>

  <tbody>

  <tr >

    <th>语言</th>

    <th>百分比</th>

    <th>票数</th>

  </tr>

  <tr>

    <td><span id="xuanshou0"></span></td>

    <td><span id="baifenbi0"></span><img id="img0" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu0"></span></td>

  </tr>

  <tr>

    <td><span id="xuanshou1"></span></td>

    <td><span id="baifenbi1"></span><img id="img1" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu1"></span></td>

  </tr>

  <tr>

    <td><span id="xuanshou2"></span></td>

    <td><span id="baifenbi2"></span><img id="img2" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu2"></span></td>

  </tr>

   <tr>

    <td><span id="xuanshou3"></span></td>

    <td><span id="baifenbi3"></span><img id="img3" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu3"></span></td>

  </tr>

 

  </tbody>

</table>

共<span id="totalCount"></span>条投票<br/>

[<span onClick="javascript:window.close();">关闭窗口</span>]

</div>

</body>

</html>

 


只有注册用户登录后才能发表评论。


网站导航:
 

posts - 146, comments - 143, trackbacks - 0, articles - 0

Copyright © flustar