首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

dwr3 学习札记<一>

2012-12-25 
dwr3 学习笔记一直接上代码,请下载源代码[在最后],有问题发我邮件lyk_52199@163.comjsp/javascript

dwr3 学习笔记<一>
直接上代码,请下载源代码[在最后],有问题发我邮件lyk_52199@163.com
<==jsp/javascript================================>
-->main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>  <title>DWR3.0DEMO--BY JUSTIN LEE @ 2011-03-13 PM</title>  <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/engine.js'></script>  <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script>  <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/Demo.js'></script>  <script type='text/javascript'>    //====================================================================================================    //无参,有简单返回值,只传一个回调参数过去    function test1(){        Demo.test1(callbackTest1);    }    /**    *test1()回调函数     **/    function callbackTest1(data){      alert(data);    }    //====================================================================================================    /*****************************************************************************************************/    //====================================================================================================    //有简单参数,无返回值    function test2(){    Demo.test2("简单参数");        //Demo.test2("简单参数",callbackTest2);//可以不用传回调函数,如果传了会得到NULL    }    /**    *test2()回调函数     **/    function callbackTest2(data){      alert(data);    }    //====================================================================================================    /*****************************************************************************************************/    //====================================================================================================    //有简单参数,有简单返回值    function test3(){        Demo.test3("有简单参数,有简单返回值",callbackTest3);    }    /**    *test3()回调函数     **/    function callbackTest3(data){      alert(data);    }    //====================================================================================================     /*****************************************************************************************************/    //====================================================================================================    //有简单参数,返回Bean类    function test4(){        Demo.test4(new Date(),callbackTest4);//这里参数是一个日期,就直接用JS的日期就可以了    }    /**    *test4()回调函数     **/    function callbackTest4(data){      //对于返回实体类的JS处理方法      if(data){      for(var property in data){  alert("property:"+property);  alert(property+":"+data[property]); }       }      //如果知道属性,则可以用下面的方法来获取值      alert(data["propA"]);      alert(data.propD[0]);//这种方式处理也可以,不过这里propD是一个数组,因此可以用数组的处理方法          }    //====================================================================================================     /*****************************************************************************************************/    //====================================================================================================    //有Bean参数,有简单返回值    function test5(){    var pa = "a String";//private String propA;var pb = 23;//private Integer propB;var pc = new Date();//private Date propC;var pd = ["a","b","c"];//private String[] propD;var obja = {propA:pa, propB:pb,propC:pc, propD:pd};//JSON方式构造一个类对象        Demo.test5(obja,callbackTest5);    }    /**    *test5()回调函数     **/    function callbackTest5(data){    alert(data);    }    //====================================================================================================     /*****************************************************************************************************/    //====================================================================================================    //有简单参数,返回LIST MAP OR SET集合类    function test6(){           Demo.test6("有简单参数,返回LIST MAP OR SET集合类",callbackTest6);    }    /**    *test6()回调函数     **/    function callbackTest6(data){    //不知道属性名称时,使用如下方法,最好少一点alert,很烦的  for(var i=0;i<data.length;i++){  for(var property in data[i]){  //alert("property:"+property);  alert("property:"+property+"--value:"+data[i][property]);  }  }     //知道属性名称时,使用如下方法  for(var i=0;i<data.length;i++){  alert(data[i].propA);  alert(data[i].propB);    alert(data[i].propD[0]);      }    }    //====================================================================================================     /*****************************************************************************************************/    //====================================================================================================    //有List、Set或者Map等集合参数,返回LIST MAP OR SET集合类    function test7(){     var pa = "1a String for test7";//private String propA;var pb = 11;//private Integer propB;var pc = new Date();//private Date propC;var pd = ["aforTest7","bforTest7","cforTest7"];//private String[] propD;var obja = {propA:pa, propB:pb,propC:pc, propD:pd}; pa = "2a String for test7";//private String propA; pb = 22;//private Integer propB; pc = new Date();//private Date propC; pd = ["2aforTest7","2bforTest7","2cforTest7"];//private String[] propD;var objb = {propA:pa, propB:pb,propC:pc, propD:pd};var list = [obja,objb];Demo.test7(list,callbackTest7);      }    /**    *test7()回调函数     **/    function callbackTest7(data){    //不知道属性名称时,使用如下方法  for(var i=0;i<data.length;i++){  for(var property in data[i]){  alert("--data["+i+"]--property:"+property+"----value:"+data[i][property]);  }  }    }    //====================================================================================================  </script></head><body onload="test7()"></body></html> 

-->upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>  <title>DWR3.0DEMO--BY JUSTIN LEE @ 2011-03-13 PM - file upload</title>      <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/UploadFile.js'></script>  <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/engine.js'></script>  <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script><script type="text/javascript">/**文件上传Dwr*/function uploadFiles() {if(document.getElementById("uploadFile").value==""){alert("请先选择要上传的文件");document.getElementById("uploadFile").click();return;}var file = dwr.util.getValue('uploadFile');UploadFile.upload(file,function(data){alert(data);document.getElementById("uploadFile").value="";//for(var property in data){  //alert("property:"+property);  //alert(property+":"+data[property]); //} });    }  </script></head><body><table><tr>        <td>File</td>        <td><input type="file" id="uploadFile" /></td>        <td id="file.container">&nbsp;</td>      </tr>      <tr>        <td colspan="3">          <button onclick="uploadFiles()">upload</button>        </td>      </tr></table></body></html>

-->dodnload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>  <title>DWR3.0DEMO--BY JUSTIN LEE @ 2011-03-13 PM</title>      <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/DownloadFile.js'></script>  <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/engine.js'></script>  <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script><script type="text/javascript">/**文件下载Dwr*/function downloadPdfFile() {  var pdftext = dwr.util.getValue('pdftext');  DownloadFile.downloadPdfFile(pdftext, function(data) {    dwr.engine.openInDownload(data);  });}  </script></head><body><input type="text" id="pdftext" value="Hello, justin Lee,这是一个PDF文档内容"  /><input type="button" onclick="downloadPdfFile()" value="DownLoadIt" /></body></html> 

<==java类================================>
TestBean.java
/** * 测试Bean */package com.justin.dwrdemo;import java.util.Date;/** * @author Administrator * */public class TestBean {private String propA;private Integer propB;private Date propC;private String[] propD;public String getPropA() {return propA;}public void setPropA(String propA) {this.propA = propA;}public Integer getPropB() {return propB;}public void setPropB(Integer propB) {this.propB = propB;}public Date getPropC() {return propC;}public void setPropC(Date propC) {this.propC = propC;}public String[] getPropD() {return propD;}public void setPropD(String[] propD) {this.propD = propD;}}

UploadFile.java
/** *  */package com.justin.dwrdemo;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import org.directwebremoting.WebContext;import org.directwebremoting.WebContextFactory;import org.directwebremoting.io.FileTransfer;/** * @author justin * */public class UploadFile {/** * 文件上传 *  * @return */public String upload(FileTransfer fileTransfer) {if(fileTransfer!=null){System.out.println("---fileTransfer.getFilename()\t"+fileTransfer.getFilename());System.out.println("---fileTransfer.getSize()\t"+fileTransfer.getSize());System.out.println("---fileTransfer.getMimeType()\t"+fileTransfer.getMimeType());}String s = "{文件上传失败}";try {WebContext webContext = WebContextFactory.get();webContext.getHttpServletResponse().setCharacterEncoding("UTF-8");String saveurl = webContext.getHttpServletRequest().getSession().getServletContext().getRealPath("/upload");System.out.println("---saveurl\t"+saveurl);String fn =  fileTransfer.getFilename();fn = new String(fn.getBytes("ISO-8859-1"), "UTF-8");File saveDir = new File("F://flexJavaDev/tomcat6_20110114/webapps/dwrDemo/uploadFiles");if(!saveDir.exists()){saveDir.mkdir();}File file = new File(saveDir.getAbsolutePath()+"/"+fn);System.out.println("fileAbsPath:"+file.getAbsolutePath());file.setReadable(true);file.setWritable(true);if (!file.exists()) {file.createNewFile();System.out.println("new File:"+file.getAbsolutePath());}InputStream inputStream = fileTransfer.getInputStream(); int available = inputStream.available();byte[] b = new byte[available];FileOutputStream foutput = new FileOutputStream(file);inputStream.read(b);foutput.write(b);foutput.flush();foutput.close();inputStream.close();s="{文件名:'"+fn+",文件类型:'"+fileTransfer.getMimeType()+"',文件大小:'"+fileTransfer.getSize()+"',文件存储地址:'"+file.getAbsolutePath()+"'}";System.out.println("===s===\n"+s);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch(Exception e){e.printStackTrace();}return s;}}

DwrDemo.java
package com.justin.dwrdemo;import java.util.*;/** * @author justin * 功能:dwr3功能性测试类 * 日期:2011-03-13 PM */public class DwrDemo {/** * 无参,有简单返回值 * @return */public String test1(){System.out.println("test1:无参,有简单返回值\t");return "test1:无参,有简单返回值";}/** * 有简单参数,无返回值 * @param s */public void test2(String s){System.out.println("test2:有简单参数,无返回值\t"+s);}/** * 有简单参数,有简单返回值 * @param s * @return */public String test3(String s){System.out.println("test3:有简单参数,有简单返回值\t"+s);return "test3:"+s;}/** * 有简单参数,返回Bean类 * @param date * @return */public TestBean test4(Date date){System.out.println("test4:有简单参数,返回一般实体类\t"+date);TestBean tb = new TestBean();tb.setPropA("string prop a");tb.setPropB(2);Calendar c = Calendar.getInstance();c.add(Calendar.YEAR, 200);tb.setPropC(c.getTime());String[] a = new String[2];a[0]="arrValue_0";a[1]="数组值_1";tb.setPropD(a);return tb;}/** * 有Bean参数,有简单返回值 * @param tb * @return */public String test5(TestBean tb){System.out.println("test5:"+tb);System.out.println(tb.getPropA());System.out.println(tb.getPropB());System.out.println(tb.getPropC());System.out.println(tb.getPropD()[0]);return "OK";}/** * 有简单参数,返回LIST MAP OR SET集合类 * @param a * @return */public List<TestBean> test6(String a){System.out.println("test6:有简单参数,返回LIST MAP OR SET集合类\t"+a);TestBean tb = null;List<TestBean> list = new ArrayList<TestBean>();for(int i=0;i<10;i++){tb = new TestBean();tb.setPropA("propA__"+i);tb.setPropB(i);tb.setPropC(new Date());String[] arr = new String[2];arr[0]="arr0__"+i;arr[1]="arr1__"+i;tb.setPropD(arr);list.add(tb);}return list;}/** * 有List、Set或者Map等集合参数,返回LIST MAP OR SET集合类 * @param a * @return */public List<TestBean> test7(List<TestBean> list){System.out.println("test7:有List、Set或者Map等集合参数,返回LIST MAP OR SET集合类\t"+list);TestBean tb = null;List<TestBean> listRs = new ArrayList<TestBean>();if(list!=null){for(int i=0;i<list.size();i++){tb = list.get(i);tb.setPropA(tb.getPropA()+"forReturn!");tb.setPropB(tb.getPropB()+1000);tb.setPropC(new Date());String[] arr = tb.getPropD();for(int j=0;j<arr.length;j++){arr[j] = arr[j]+"updatedByTest7()";}tb.setPropD(arr);listRs.add(tb);}}return list;}}

DownFile.java
/** *  */package com.justin.dwrdemo;import java.io.ByteArrayOutputStream;import org.directwebremoting.io.FileTransfer;import com.lowagie.text.Document;import com.lowagie.text.Paragraph;import com.lowagie.text.pdf.PdfWriter;/** * @author justin * */public class DownloadFile {public FileTransfer downloadPdfFile(String contents) throws Exception {    if (contents == null || contents.length() == 0) {        contents = "[BLANK]";    }    ByteArrayOutputStream buffer = new ByteArrayOutputStream();    Document document = new Document();    PdfWriter.getInstance(document, buffer);    document.addCreator("created by justin Lee with iText");    document.open();    document.add(new Paragraph(contents));    document.close();    return new FileTransfer("justinLeePdfDemo.pdf", "application/pdf", buffer.toByteArray());}}

----------------------------------------------------by justin Lee @2011-03-13 PM

热点排行