struts2+ajax+json 实例

1、struts2 要支持json,需要先引入包,包的下载地址如下:

http://code.google.com/p/jsonplugin/downloads/list

2、根据struts2的版本,选择jar包。

3、配置struts.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="TestJson" extends="json-default,struts-default" namespace="/bbs">
		<action name="GoView" class="com.json.action.JsonAction" method="goView">
			<result name="success">/GOView.jsp</result>
		</action>
		
		<action name="getUserName" class="com.json.action.JsonAction" method="getUserName">
			<result type="json"/>
		</action>
	</package>	
</struts>

 

4、JAVA类信息如下:

public class JsonAction extends ActionSupport {

	private static final long serialVersionUID = 105155412743741566L;
	
	private User		user;
	
	public String goView() throws Exception {
		return SUCCESS;
	}

	public String getUserName() throws Exception {
		return SUCCESS;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}

 

5、JSP页面如下:

 

<!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="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">    		
		<title>JSON学习</title>
		<script language="javascript" type="text/javascript" src="<%=basePath%>JQuery/jquery-1.6.js"></script>
		<script type="text/javascript">
			function testJSON() {
				var username = "isoftstone";
				$.ajax({
					type:'post',
					url:'bbs/getUserName.action',
					dataType:'json',
					data:{
						"user.username":username
					},
					success:function(msg){
						alert(msg.user.username);
					}
				});
			}
		</script>
	</head>
	<body>
		<input type="button" value="测试JSON" onClick="JavaScript:testJSON()"/>
	</body>
</html>

 

6、运行程序及可。

7、注意事项:

(1) 引入的包要正确;

(2) struts.xml的package定义要正确:

<package name="TestJson" extends="json-default,struts-default" namespace="/bbs">

 

(3) JQuery 使用ajax 接受数据的格式是:JSON。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值