首先定义一个javascript函数,用来验证注册时用户名是否已经存在
function validateName(){
//validateName值得是structs.xml中的名字是validateName那个action,在spring配置文件中注入
var url = 'validateName!execute';
var json = document.getElementById("name").value;//获取用户名
var jsonName = {name:json}//创建json对象
var name = JSON.stringify(jsonName); //将json对象转换成json格式的字符串
$.post(url, {json: name}, function(json){
$("#tip").text(json.msg); }, "json");
}
看看具体的ValidateAction实现
package org.arthur.lr.system.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.arthur.lr.system.dao.UserManager;
import org.json.JSONObject;
import com.googlecode.jsonplugin.annotations.JSON;
import com.opensymphony.xwork2.ActionSupport;
public class ValidateAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
//这个属性已经在spring配置文件中注入,千万不要在这里写UserManger mgr = new UserMangerImpl();
private UserManager mgr;
private String json;
@JSON
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
public UserManager getMgr() {
return mgr;
}
public void setMgr(UserManager mgr) {
this.mgr = mgr;
System.out.println("启动tomcat时初始化");
}
@Override
public String execute() throws Exception {
JSONObject jsonObj = new JSONObject(json); //将JSON格式的字符串构造成JSON对象
String name = jsonObj.getString("name"); //获取JSON对象中的name属性的值
if (mgr.validateName(name)) {
json = "{msg:'you can use this name to regist'}";
System.out.println("有户名有效");
} else {
json = "{msg:'the name is already exits'}";
System.out.println("用户名已经存在");
}
this.sendMsg(json);//发送数据到客户端,供回调函数调用
return SUCCESS;
}
public void sendMsg(String msg) throws IOException{
System.out.println("发送json");
HttpServletResponse res = ServletActionContext.getResponse();
PrintWriter out = res.getWriter();
//out.println(msg);这样写也行
out.write(msg);
if(null != out){
out.close();//如果不关闭的话,ajax的回调函数不会调用
}
}
}