首先导入包
json-lib-2.1.jar
struts2-json-plugin-2.1.8.1.jar(这两个是JSON所必须的包)
ezmorph-1.0.3.jar, commons-collections-3.2.jar
commons-beanutils-1.7.0.jar
commons-logging-1.0.4.jar
commons-lang-2.3.jar (因为json大量引用了Apache commons的包,所以需要引入commons的四个包。)
然后看action:
public class RegisterAction extends ActionSupport implements RequestAware, SessionAware
{
IUserDao iud = new UserDaoImpl();
private Map<String, Object> request;
private Map<String, Object> session;
private String name;
private String pwd;
private String rpwd;
private String gender;
private String head;
private String code;
private String tip; // ajax返回的结果
public String execute()
{
int genderInt = Integer.parseInt(gender);
String serCode = session.get("validateCode").toString();
// 验证码输入正确
if (serCode.equals(code))
{
User u = new User();
u.setGender(genderInt);
u.setHead(head);
u.setPassWord(pwd);
u.setRegTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date()));
u.setUserName(name);
iud.addUser(u);
tip="注册成功,登录去吧";
}
else
{
tip="验证码不正确";
}
return SUCCESS;
}
..........省略get set
}
struts.xml--这里还使用的是Struts自带的ajax
<package name="ajax" namespace="/" extends="json-default">
<action name="regSub" class="com.xy.action.RegisterAction">
<result type="json">
</result>
</action>
</package>
jsp:
$("#btnSubmit").click(function(){
var uname = $("#txtUserName").val();
var pwd = $("#txtPwd").val();
var rpwd = $("#txtRepeatPwd").val();
var gender = $("input[name=gender]:checked").val();
var head = $("input[name=head]:checked").val();
var code = $("#txtCode").val();
$.get("regSub", {
name: uname,
pwd: pwd,
rpwd: rpwd,
gender:gender,
head:head,
code:code
}, function (data, status) {
$('#hint').html(data.tip);
});
})
<table height="100px" id="register">
<tr>
<td align="right">
用 户 名
</td>
<td align="left">
<input id="txtUserName" type="text" maxlength="10"style="width: 150px" />
</td>
</tr>
<tr>
<td align="right">
密码
</td>
<td align="left">
<input id="txtPwd" type="password" maxlength="10" style="width: 150px" />
</td>
</tr>
<tr>
<td align="right">
重复密码
</td>
<td align="left">
<input id="txtRepeatPwd" type="password" maxlength="10" style="width: 150px" />
</td>
</tr>
<tr>
<td align="right">
性别
</td>
<td align="left">
<input id="man" type="radio" name="gender" checked="true"value="1" />
<label for="man">
男
</label>
<input id="woman" type="radio" name="gender" value="2" />
<label for="woman">
女
</label>
</td>
</tr>
<tr>
<td align="right">
验证码
</td>
<td align="left">
<input id="txtCode" type="text" style="width: 150px" />
<img id="imgCode" src="toCode" />
<a href="javascript:change()"> 看不清,换一张</a>
<input type="button" id="btnSubmit value="注册"/> // 注意哦,是button类型,不是submit
</td>
</tr>
</table>
还有一种方式在Struts中使用ajax,请参看我的博文《struts2中使用ajax之二》。