日期:2014-05-16 浏览次数:20432 次
本文主要是演示一下怎么在 jquery + struts2 下使用json 来传数据,实现的效果很简单,在页面输入 “用户编号”和“用户名称” 下面用一个层来显示。
首先是regist.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Regist.jsp</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">
<script type="text/javascript" src="<%=basePath %>script/jquery-1.3.2.js"></script>
<script language="javascript" type="text/javascript">
function showPersonInfo()
{
var authorid = $("#authorid").val();
var authorname=$("#authorname").val();
var url ="<%=request.getContextPath() %>/personAjaxAction.action";
$.post(url,{authorid:authorid,authorname:authorname},callback,"json");
}
function callback(data)
{
var rs = data.person
var html = "";
html+="<table><tr><td>用户编号:</td><td>"+rs.authorid+"</td></tr><tr><td>用户名称:</td> <td>"+rs.authorname+"</td></tr>";
$("#showPersonInfo").html(html);
}
</script>
</head>
<body>
<form method="post">
用户编号:<input type="text" id="authorid" name="person.authorid"/><br>
用户名称:<input type="text" id="authorname" name="person.authorname"/><br>
<input type="button" value="ajax" name="ajaxsubmit" onclick="showPersonInfo();"/>
</form>
<div id="showPersonInfo"></div>
</body>
</html>
?
web.xml的配置:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Struts 2.0 Hello World</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
?
struts.xml 的配置:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<!--
<package name="tutorial" extends="struts-default">
<action name="personAction" class="tutorial.entity.PersonAction">
<result>/regist.jsp</result>
</action>
</package>
-->
<package name="personjson" extends="json-default" namespace="/">
<action name="personAjaxAction" class="tutorial.entity.PersonAction" method="showPersonInfo">
<result type="json"/>
</action>
</package>
</struts>
?PersonAction 的源码:
package tutorial.entity;
import javax.servlet.http.Http