1.准备工作
①ajax使用Jquery:jquery-1.4.2.min.js
②struts2与json的依赖包:struts2-json-plugin-2.2.3.jar
PS:版本可自己控制!~
2.过程
①引入json依赖包
②编写action类
③配置struts.xml
④编写页面
⑤测试
3.实例
①页面ajax写法,json.jsp
<%@ page language=
"java"
contentType=
"text/html; charset=UTF-8"
pageEncoding=
"UTF-8"
%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+
"://"
+request.getServerName()+
":"
+request.getServerPort()+path+
"/"
;
%>
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"
>
<html>
<head>
<base href=
"<%=basePath%>"
>
<meta http-equiv=
"Content-Type"
content=
"text/html; charset=ISO-8859-1"
>
<title>测试</title>
<script type=
"text/javascript"
src=
"include/js/jquery-1.4.2.min.js"
></script>
<script type=
"text/javascript"
>
$(
function
() {
$(
"#tj"
).click(
function
() {
//提交的参数,name和inch是和struts action中对应的接收变量
var
params = {
name : $(
"#xm"
).val(),
inch : $(
"#sg"
).val()
};
$.ajax({
type:
"POST"
,
url:
"jsonAjax.action"
,
data: params,
dataType:
"text"
,
//ajax返回值设置为text(json格式也可用它返回,可打印出结果,也可设置成json)
success:
function
(json){
var
obj = $.parseJSON(json);
//使用这个方法解析json
var
state_value = obj.result;
//result是和action中定义的result变量的get方法对应的
alert(state_value);
},
error:
function
(json){
alert(
"json="
+ json);
return
false
;
}
});
});
});
</script>
</head>
<body>
<span>姓名:</span><input id=
"xm"
type=
"text"
>
<br/>
<span>身高:</span><input id=
"sg"
type=
"text"
>
<br/>
<input type=
"button"
value=
"提交"
id=
"tj"
>
</body>
</html>
import
com.opensymphony.xwork2.ActionSupport;
/**
*
* @Title: JsonAction.java
* @Package com.zxt.action
* @Description:struts2 + ajax + json用例
* @author zxt
* @date 2011-12-6 上午10:38:51
* @version V1.0
*/
public
class
JsonAction
extends
ActionSupport {
/**
*
*/
private
static
final
long
serialVersionUID = 7443363719737618408L;
/**
* 姓名
*/
private
String name;
/**
* 身高
*/
private
String inch;
/**
* ajax返回结果,也可是其他类型的,这里以String类型为例
*/
private
String result;
@Override
public
String execute()
throws
Exception {
// TODO Auto-generated method stub
if
(
"张三"
.equals(name)) {
result =
"身份验证通过,身高为"
+ inch;
}
else
result =
"不是张三!"
;
return
SUCCESS;
}
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
public
String getInch() {
return
inch;
}
public
void
setInch(String inch) {
this
.inch = inch;
}
/**
*
* @Title: getResult
* @Description:json调取结果
* @param @return
* @return String
* @throws
*/
public
String getResult() {
return
result;
}
}
③
struts配置。 struts.xml
创建一个新的package,引入json-default
<
package
name
=
"ajax"
extends
=
"json-default"
>
<
action
name
=
"jsonAjax"
class
=
"com.zxt.action.JsonAction"
>
<!-- 将返回类型设置为json -->
<
result
type
=
"json"
></
result
>
</
action
>
</
package
>
文章转自:http://www.open-open.com/lib/view/open1370959303601.html