struts2中提供了与json插件的整合,从而可以为Action指定名为json的ResultType。JSON插件会自动将Action中的信息序列化成JSON格式的数据,可以通过javaScript(或者jquery函数来调用)。下面通过实例来介绍如何通过JSON插件完成Ajax方式的用户名是否占用检测。
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<script language="JavaScript" src="js/jquery-1.6.3.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'jquery.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<DIV class=line><LABEL class=big id=lblName>用户注册</LABEL>
<INPUT id='memberid' name="memberid" ><span id="warn"></span>
</DIV>
</body>
</html>
实现业务逻辑的Action
package net.hncu.struts2.action;
import com.opensymphony.xwork2.ActionSupport;
public class MemberAction extends ActionSupport
{
private String isMemberIdUsed;
private String memberid;
public String getMemberid() {
return memberid;
}
public void setMemberid(String memberid) {
this.memberid = memberid;
}
public String getIsMemberIdUsed() {
return isMemberIdUsed;
}
public void setIsMemberIdUsed(String isMemberIdUsed) {
this.isMemberIdUsed = isMemberIdUsed;
}
// 处理用户请求的 execute 方法
public String execute() throws Exception {
System.out.println("fupdds");
if ("sky".equals(memberid)) {
this.setIsMemberIdUsed("yes");
} else {
this.setIsMemberIdUsed("no");
}
return SUCCESS;
}
}
jquery.js中的代码:
$(document).ready(function () {
$("#memberid").blur(function(){
$.post("CheckMemberId.action", { memberid:$("#memberid").val()},
function (data, textStatus){
alert(data.isMemberIdUsed);
if(data.isMemberIdUsed=="yes"){
$("#warn").html("<font color='red'>用户名已经被注册,请重新选择一个!</font>");
}
}, "json") ;
});
});
struts.xml中的配置:
<package name="strutsjson" extends="json-default">
<action name="CheckMemberId" class="net.hncu.struts2.action.MemberAction" >
<result type="json" /> //将action中的属性封装成json类型
</action>
</package>
结果如下: