日期:2014-05-16  浏览次数:20431 次

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。