基于spring+dwr+xml無刷新投票(調查)系統

          Posted on 2007-11-19 18:04 flustar 閱讀(1364) 評論(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, "http://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

          主站蜘蛛池模板: 夏河县| 晴隆县| 枣阳市| 云霄县| 新泰市| 固阳县| 绿春县| 抚松县| 扶风县| 巴彦淖尔市| 土默特右旗| 三穗县| 延长县| 保定市| 丹阳市| 柘荣县| 湖州市| 霍州市| 饶河县| 长宁区| 清水河县| 甘孜| 万全县| 定边县| 云浮市| 寻乌县| 精河县| 兴山县| 孟州市| 海林市| 汉阴县| 佳木斯市| 乳山市| 日喀则市| 沅江市| 孝义市| 九江县| 蒲江县| 南涧| 绥滨县| 大田县|