第四十三讲:tapestry Ajax表单验证

tapestry Ajax表单验证,作用非常大可做检查用户名是否存在。源码如下:

AJAXValidators1.java

/**
 * 项目名称:TapestryStart
 * 开发模式:Maven+Tapestry5.x+Tapestry-hibernate+Mysql
 * 网址: http://www.flywind.org
 * 版本:1.0
 * 编写:飞风
 * 时间:2012-02-29
 */
package com.tapestry.app.pages;
 
import java.util.List;
 
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.Request;
 
import com.tapestry.app.entities.Person;
import com.tapestry.app.services.StartDAO;
 
public class AJAXValidators1 {
@Property
private String firstName;
 
@Property
private String lastName;
 
@Property
@SuppressWarnings("unused")
private List<Person> persons;
 
@InjectPage
private AJAXValidators2 page2;
 
@Inject
private Request request;
 
@Inject
private StartDAO dao;
 
void setupRender() {
StringBuffer sql = new StringBuffer();
sql.append("from Person");
persons = dao.findWithQuery(sql.toString());
}
 
JSONObject onAjaxValidateFromFirstName() {
String firstName = request.getParameter("param");
 
try {
validateFirstNameIsUnique(firstName);
}
catch (Exception e) {
return new JSONObject().put("error", e.getMessage());
}
 
return new JSONObject();
}
 
Object onSuccess() {
page2.set(firstName, lastName);
return page2;
}
 
void validateFirstNameIsUnique(String firstName) throws Exception {
if (firstName != null) {
List<Person> persons = dao.searchQuery(firstName);
 
if (persons.size() > 0) {
throw new Exception("姓已经存在.");
}
}
}
 
}
 

AJAXValidators1.tml

<html t:type="layout" title="tapestryStart Index"  t:sidebarTitle="Framework Version" 
xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd" xmlns:p="tapestry:parameter">
<div style="margin: 20px;">
<form t:type="CustomForm" t:id="inputs">
<t:errors/>
<table>
<tr>
<td><t:label for="firstName"/>:</td>
<td><input t:type="TextField" t:id="firstName" t:validate="required, maxlength=10" size="10"
t:mixins="ajaxValidator"/></td>
<td>(required, maxLength=10, new name only)</td>
</tr>
<tr>
<th></th>
<td colspan="2"><t:customerror for="firstName"/></td>
</tr>
<tr>
<td><t:label for="lastName"/>:</td>
<td><input t:type="TextField" t:id="lastName" t:validate="required, maxLength=10" size="10"/></td>
<td>(required, maxLength=10, new name only)</td>
</tr>
<tr>
<th></th>
<td colspan="2"><t:customerror for="lastName"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Display"/></td>
<td></td>
</tr>
</table>
</form><br/>
<table t:type="grid" t:source="persons" t:row="var:person" include="firstName,lastName">[Grid here]</table>
</div>
</html>

AjaxValidator.java

/**
 * 项目名称:TapestryStart
 * 开发模式:Maven+Tapestry5.x+Tapestry-hibernate+Mysql
 * 网址: http://www.flywind.org
 * 版本:1.0
 * 编写:飞风
 * 时间:2012-02-29
 */
package com.tapestry.app.mixins;
 
import org.apache.tapestry5.ClientElement;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
 
@Import(library = "context:assets/js/AjaxValidator.js")
public class AjaxValidator {
@Inject
private ComponentResources componentResources;
 
@Inject
private JavaScriptSupport javaScriptSupport;
 
@InjectContainer
private ClientElement clientElement;
 
void afterRender() {
 
JSONObject spec = new JSONObject();
spec.put("elementId", clientElement.getClientId());
spec.put("listenerURI", componentResources.createEventLink("ajaxValidate").toAbsoluteURI());
javaScriptSupport.addInitializerCall("ajaxValidator", spec);
}
}
 

AjaxValidator.js

AjaxValidator = Class.create( {
 
initialize : function(spec) {
this.field = $(spec.elementId);
this.listenerURI = spec.listenerURI;
 
// Set up a listener that validates the field - asynchronously in the server - on change of focus
 
document.observe(Tapestry.FOCUS_CHANGE_EVENT, function(event) {
 
// If changing focus *within the same form* then perform validation.  
// Note that Tapestry.currentFocusField does not change
// until after the FOCUS_CHANGE_EVENT notification.
 
if (Tapestry.currentFocusField == this.field && this.field.form == event.memo.form) {
this.asyncValidateInServer();
}
 
}.bindAsEventListener(this) );
},
 
asyncValidateInServer : function() {
var value = this.field.value;
var listenerURIWithValue = this.listenerURI;
   
if (value) {
listenerURIWithValue = addRequestParameter('param', value, this.listenerURI);
 
new Ajax.Request(listenerURIWithValue, {
method: 'get',
onFailure: function(t) {
   alert('Error communication with the server: ' + t.responseText.stripTags());
},
onException: function(t, exception) {
   alert('Error communication with the server: ' + exception.message);
},
onSuccess: function(t) {
if (t.responseJSON.error) {
this.field.showValidationMessage(t.responseJSON.error);
}
}.bind(this)
});
}
}
 
} )
 
function addRequestParameter(name, value, url) {
if (url.indexOf('?') < 0) {
url += '?'
} else {
url += '&';
}
value = escape(value);
url += name + '=' + value;
return url;
}
 
// Extend the Tapestry.Initializer with a static method that instantiates an AjaxValidator.
 
Tapestry.Initializer.ajaxValidator = function(spec) {
    new AjaxValidator(spec);
}

AJAXValidators2.java

/**
 * 项目名称:TapestryStart
 * 开发模式:Maven+Tapestry5.x+Tapestry-hibernate+Mysql
 * 网址: http://www.flywind.org
 * 版本:1.0
 * 编写:飞风
 * 时间:2012-02-29
 */
package com.tapestry.app.pages;
 
public class AJAXValidators2 {
private String firstName;
 
private String lastName;
 
public void set(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
 
 
String[] onPassivate() {
return new String[] { firstName, lastName };
}
 
void onActivate(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
 
public String getName() {
return firstName + " " + lastName;
}
}
 

AJAXValidators2.tml

<html t:type="layout" title="tapestryStart Index"  t:sidebarTitle="Framework Version" 
xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd" xmlns:p="tapestry:parameter">
你好, ${name}
</html>

转载于:https://my.oschina.net/shootercn/blog/55530

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值