dwr @DataTransferObject与@RemoteProperty的应用

来源:互联网 发布:ff14猫男捏脸数据 编辑:程序博客网 时间:2024/04/29 23:24

在<<DWR Annotation入门>>中已简单介绍了dwr的使用,对于其中涉及到的两个注解@DataTransferObject和@RemoteProperty,本文将进一步介绍

@DataTransferObject对应于原来dwr.xml文件中的convert标签,用于转换Java对象;

@RemoteProperty则对应于convert标签中的 <param name=”include” value=”" />。


本文在<<DWR Annotation入门>>基本中新建类Entity,代码如下

package model;import org.directwebremoting.annotations.DataTransferObject;import org.directwebremoting.annotations.RemoteProperty;@DataTransferObjectpublic class Entity {private String id="";private String title="";@RemotePropertypublic String getId() {return id;}public void setId(String id) {this.id = id;}@RemotePropertypublic String getTitle() {return title;}public void setTitle(String title) {this.title = title;}}

 

然后修改Test.java,   新建方法getEntity(Entity entity)

package model;import org.directwebremoting.annotations.RemoteMethod;import org.directwebremoting.annotations.RemoteProxy;@RemoteProxy( name="test")public class Test {@RemoteMethod  public String getString(String para){return "return "+para;}@RemoteMethod  public Entity getEntity(Entity entity){if(entity==null)entity=new Entity();entity.setId("return "+entity.getId());entity.setTitle("return " +entity.getTitle());return entity;}}



修改配置文件web.xml, 增加classes参数的内容

<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>        <init-param>            <param-name>classes</param-name>            <param-value>           model.Test,model.Entity            </param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>dwr-invoker</servlet-name>        <url-pattern>/dwr/*</url-pattern>    </servlet-mapping>


最后我们再来看看在jsp页面中如何使用,再下面的代码中,我们选创建js对象para,然后将para作为参数传入getEntity()

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <script type='text/javascript' src='/TestDwr/dwr/engine.js'></script>  <script type='text/javascript' src='/TestDwr/dwr/interface/test.js'></script>   <script type="text/javascript">  var para={}; para["id"]="2"; para["title"]="3";  test.getEntity( para,//getString的参数 function(data){document.write('id:'+data["id"]+'<br/>'+'title:'+data["title"]);}//当getString从服务器取回数据后的回调函数,data为返回的值 ); </script>      </head>    <body>  </body></html>

最后,就可以运行该web程序了

 

原创粉丝点击