dwr学习之 二、dwr功能演示

dwr学习之 二、dwr功能演示

 

转处:http://limingnihao.iteye.com/blog/1074204

 

文中代码均已简化。

1. hello world

         定义DWRDemo类,并使用注解声明方式。

Java代码   收藏代码
  1. @Service  
  2. @RemoteProxy(name = "DWRDemo")  
  3. public class DWRDemo {  
  4.   
  5.     private static final Logger LOGGER = LoggerFactory.getLogger(DWRDemo.class);  
  6.   
  7.     /** 
  8.      * 1. 基本调用,参数字符串,返回字符串 
  9.      *  
  10.      * @param test 
  11.      * @return 
  12.      * @throws Exception 
  13.      */  
  14.     @RemoteMethod  
  15.     public String sayHello(String test) throws Exception {  
  16.         LOGGER.info("DWRDemo sayHello, test: " + test);  
  17.         if (test.equals("error")) {  
  18.             throw new Exception("出现异常");  
  19.         }  
  20.         return "Java: " + test;  
  21.     }  
  22. }  
 

 

 

    js端首先导入dwr所需的js文件

Html代码   收藏代码
  1. <script type='text/javascript' src='<%=request.getContextPath() %>/dwr/interface/DWRDemo.js'></script>  
  2. <script type='text/javascript' src='<%=request.getContextPath() %>/dwr/engine.js'></script>  
  3. <script type='text/javascript' src='<%=request.getContextPath() %>/dwr/util.js'></script>  
 

 

    js调用DWRDemosayHello方法:

Js代码   收藏代码
  1. DWRDemo.sayHello("我是js"function(data){  
  2.     alert(data);  
  3. });  
 

 

    还可以定义超时时间,和错误方法:

Js代码   收藏代码
  1. DWRDemo.sayHello("error", {  
  2.     callback: function(data){  
  3.         alert(data);  
  4.     },  
  5.     timeout: 1000,  
  6.     errorHandler:function(error){  
  7.         alert(error);  
  8.     }  
  9. });  
 

 

 

2. 调用参数为实体类

         使用@DataTransferObject( 或dwr:conver t) 声明实体类。

Java代码   收藏代码
  1. package liming.student.manager.web.model;  
  2.   
  3. import org.directwebremoting.annotations.DataTransferObject;  
  4. import org.directwebremoting.io.FileTransfer;  
  5. import org.springframework.web.multipart.MultipartFile;  
  6.   
  7. @DataTransferObject  
  8. public class StudentForm extends GeneralForm {  
  9.     private String studentName;  
  10.     private int studentSex;  
  11.     private String studentBirthday;  
  12.     private FileTransfer studentPhoto_dwr;  
  13.     private String classId;  
  14.     private String placeId;  
  15.   
  16. }  
 

 

 

    java方法使用此实体类作参数:

Java代码   收藏代码
  1. @Service  
  2. @RemoteProxy(name = "StudentDWR")  
  3. public class StudentDWR {  
  4.   
  5.     @RemoteMethod  
  6.     public boolean addStudent(StudentForm form) {  
  7.   
  8.         //代码省略  
  9.   
  10.     }  
  11. }  
 

 

 

    js端调用:

Js代码   收藏代码
  1. var student = {  
  2.     studentName: $("#studentName").val(),  
  3.     studentSex: $("#studentSex").val(),  
  4.     studentBirthday: $("#studentBirthday").val(),  
  5.     studentPhoto_dwr: dwr.util.getValue("studentPhoto"),  
  6.     classId: "1",  
  7.     placeId: "1"  
  8. };  
  9. StudentDWR.addStudent(student, function(data){  
  10.     if( data == true ){  
  11.         alert("dwr新增学生成功!");  
  12.         window.location = "<%=request.getContextPath()%>/student/list.do";  
  13.     }else{  
  14.         alert("dwr新增学生失败!");  
  15.     }  
  16. });  
 

 

 

3. 获取实体类或列表

         使用@DataTransferObject( 或dwr:conver t) 声明实体类。

Java代码   收藏代码
  1. @DataTransferObject  
  2. public class StudentEntity implements Serializable {  
  3.     private String studentId;  
  4.     private String studentName;  
  5.     private int studentSex;  
  6.     private Date studentBirthday;  
  7.     private String photoId;  
  8.     private String classId;  
  9.     private String placeId;  
  10.   
  11. }  
 

 

 

         java方法直接返回此实体类或列表:

Java代码   收藏代码
  1. @RemoteMethod  
  2. public List<StudentEntity> getStudentBaseAllList() {  
  3.     return this.studentService.getStudentBaseAllList(0, StudentForm.DEFAULT_PAGE_SEZE, "");  
  4. }  
 

 

 

         在js端直接调用此方法后,得到的数据为json格式的object,可以直接调用属性。

Js代码   收藏代码
  1. StudentDWR.getStudentBaseAllList(function(data){   
  2.     studentList = data;  
  3.     for(var i=0; i<data.length; i++){  
  4.         var studentId = data[i].studentId;  
  5.         var studentName = data[i].studentName;  
  6.         var studentSex = data[i].studentSex;  
  7.         var studentBirthday = data[i].studentBirthday;  
  8.         var classId = data[i].classId;  
  9.         var placeId = data[i].placeId;  
  10.         var photoId = data[i].photoId;  
  11.     }  
  12. });  
 

 

 

4. 导入页面

         java代码写法:

Java代码   收藏代码
  1. @RemoteMethod  
  2. public String includeHtmlPage(String url) throws ServletException, IOException {  
  3.     LOGGER.info("DWRDemo includeHtmlPage, url: " + url);  
  4.     WebContext wctx = WebContextFactory.get();  
  5.     return wctx.forwardToString(url);  
  6. }  
 

 

 

         js调用:

Js代码   收藏代码
  1. DWRDemo.includeHtmlPage("/templet/add.jsp"function(data) {  
  2.     dwr.util.setValue("forward", data, { escapeHtml:false });  
  3. });  
 

 

        html中定义一个idforwarddiv

Html代码   收藏代码
  1. <div id="forward"></div>  
 

 

 

5. 上传文件

       使用DWR上传文件需要注意的几点:

  1.  java方法的参数必须是BufferedImage,InputStream,FileTransfer三种中其中一个,一般推荐使用FileTransfer,可以获取文件名、文件类型、和内置的inputStream;

  2.  js端使用dwr.util.getValue方法获取的obj当参数;

  3.  不能与springMVC的上传文件兼容。(不能在spring配置文件中声明org.springframework.web.multipart.commons.CommonsMultipartResolver的bean);

  4.  web.xml中的filter-mapping的url-pattern尽量不要使用/*,写成具体的,例如:*.do。

 

       下面代码为将上传的文件使用createStringPhoto方法保存到数据库,并且进行缩小并返回。

Java代码   收藏代码
  1. @RemoteMethod  
  2. public BufferedImage uploadPhtoFile(FileTransfer file) {  
  3.     try {  
  4.         if (file.getSize() > Integer.MAX_VALUE) {  
  5.             return null;  
  6.         }  
  7.         LOGGER.info("DWRDemo uploadPhtoFile, file: " + file.toString());  
  8.         InputStream input = file.getInputStream();  
  9.         byte[] photoData = new byte[(int) file.getSize()];  
  10.         input.read(photoData);  
  11.         input.close();  
  12.         this.studentService.createStringPhoto(photoData, file.getFilename());  
  13.         BufferedImage image = scaleImageBytesToBufferedImage(photoData, 100100);  
  14.         return image;  
  15.     } catch (Exception e) {  
  16.         e.printStackTrace();  
  17.     }  
  18.     return null;  
  19. }  
  20.   
  21. public static BufferedImage scaleImageBytesToBufferedImage(byte[] data, int width, int height) throws IOException {  
  22.     BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));  
  23.     int imageOldWidth = buffered_oldImage.getWidth();  
  24.     int imageOldHeight = buffered_oldImage.getHeight();  
  25.     double scale_x = (double) width / imageOldWidth;  
  26.     double scale_y = (double) height / imageOldHeight;  
  27.     double scale_xy = Math.min(scale_x, scale_y);  
  28.     int imageNewWidth = (int) (imageOldWidth * scale_xy);  
  29.     int imageNewHeight = (int) (imageOldHeight * scale_xy);  
  30.     BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);  
  31.     buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0,  
  32.             0null);  
  33.     buffered_newImage.getGraphics().dispose();  
  34.     return buffered_newImage;  
  35. }  

 

 

      html代码:

Html代码   收藏代码
  1. <input type="file" id="uploadImage"/>  
  2. <input type="button" onclick="uploadFile()" value="dwr上传文件"/>  
  3. <img id="image"/>  
 

 

 

      js代码,使用dwr.util.getValue获取文件对象上传文件,使用dwr.util.setValue方法设置显示图片。

Js代码   收藏代码
  1. function uploadFile(){  
  2.     var image = dwr.util.getValue('uploadImage');  
  3.     DWRDemo.uploadPhtoFile(image, function(data){  
  4.         if( data != null ){  
  5.             dwr.util.setValue('image', data);  
  6.         }         
  7.     });  
  8. }  
 

 

 

6. 下载文件

         在java方法中,使用字节数组构造出一个FileTransfer对象,并返回。

         在js端,将获取到的数据当参数,调用dwr.engine.openInDownload即可。

 

java代码:

Java代码   收藏代码
  1. @RemoteMethod  
  2. public FileTransfer downloadPhotoFile(String studentId) throws Exception {  
  3.     LOGGER.info("DWRDemo downloadPhotofFile, studentId: " + studentId);  
  4.     PhotoEntity photoEntity = this.studentService.getPhotoDataByStudentId(studentId);  
  5.     if (photoEntity != null && photoEntity.getPhotoData() != null && photoEntity.getPhotoData().length > 0) {  
  6.         byte[] data = photoEntity.getPhotoData();  
  7.         String fileName = photoEntity.getFileName();  
  8.         fileName = fileName == null ? "照片" + studentId + ".png" : fileName;  
  9.         fileName = URLEncoder.encode(fileName, "UTF-8");  
  10.         return new FileTransfer(fileName, "application/octet-stream;charset=UTF-8", data);  
  11.     } else {  
  12.         return null;  
  13.     }  
  14. }  
 

      js代码:

Js代码   收藏代码
  1. DWRDemo.downloadPhotoFile("10000032"function(data){  
  2.     if( data != null ){  
  3.         dwr.engine.openInDownload(data);  
  4.     }else{  
  5.         alert("此照片不存在");  
  6.     }  
  7. });  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值