首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

struts2+ajax+json 范例

2012-08-29 
struts2+ajax+json 实例1、struts2 要支持json,需要先引入包,包的下载地址如下:http://code.google.com/p/j

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" method="goView"><result name="success">/GOView.jsp</result></action><action name="getUserName" method="getUserName"><result type="json"/></action></package></struts>

?

4、JAVA类信息如下:

public class JsonAction extends ActionSupport {private static final long serialVersionUID = 105155412743741566L;private Useruser;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。

热点排行