使用DWR在页面中调用javaBean方法存储Person对象

1、定义一个Person对象,并在这个类中定义一个savePerson方法
public class Person {
	private int id;
	private String name;
	private String sex;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String savePerson(Person p) {
		return "Person对象被保存了 " + "id=" + p.getId() + "name=" + p.getName() + "sex=" + p.getSex();
	}
}


2、配置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="new" javascript="person">
      	<param name="class" value="com.bjsxt.dwr.Person"/>
    </create>
<!--要让dwr知道这个Person是个什么类型,要加上一个转换器 -->
    <convert converter="bean" match="com.bjsxt.dwr.Person" />
  </allow>
</dwr>


3、页面中的调用
<head
    <title>My JSP 'index.jsp' starting page</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/person.js"></script>
    
	<title></title>
	<script type="text/javascript">
	 //var person = {"id":1, "name":"张三","sex":"女" };
	 
	 function person2(){
		 
			this.id=1;
			this.name="王五";
			this.sex="女";
		 }
		
		function savePerson() {
			//用这种方式构建一个Person对象也可以
			//var person1 = new Object();
			//person1.id = 3;
			//person1.name = "李四";
			//person1.sex = "男";
			
			var p = new person2();
			//保存
			person.savePerson(
					p,
					function(data) {
						alert(data) ;
					}
			);
		}
	</script>
  </head>
  
  <body>
    <a href="#" onclick="savePerson()">保存用户s</a>
  </body>

你可能感兴趣的:(html,jsp,xml,Web,DWR)