一、jar包
使用之前必须引入所须要的jar包,这里包含Struts2和JSONObject各自所必须的
Struts2:
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
freemarker-2.3.13.jar
ognl-2.6.11.jar
struts2-core-2.1.6.jar
xwork-2.1.2.jar
JSONObject:
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
ezmorph-1.0.3.jar
json-lib-2.1.jar
PS: 本例Struts2版本号为2.1.6,以上全部jar包在struts-2.1.6lib中都能够找到,
假设以上jar包是东拼西凑的 特别是JSONObject,有可能会因jar包兼容性问题而报错。
二、前台代码
<body> <form id="myform"> <table> <tr> <td>姓名:</td> <td> <input type="text" name="name" /> </td> </tr> <tr> <td>性别:</td> <td> <input type="radio" name="sex" value="1"> 男 <input type="radio" name="sex" value="0"> 女 </td> </tr> <tr> <td>年龄:</td> <td> <select name="age"> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> </select> </td> </tr> <tr> <td colspan="2"> <input type="button" id="ajaxBtn" value="提交" /> </td> </tr> </table> </form> <div id="msg"></div> </body>
<script type="text/javascript"> $(function() { $("#ajaxBtn").click(function() { var params = $("#myform").serialize(); $.ajax( { type : "POST", dataType: "json", url : "RegisterAction.action", data : params, success : function(msg) { if(msg.success == true){ $("#msg").html("您提交的信息为,姓名: "+msg.name+ ", 性别:"+msg.sex+", 年龄:"+msg.age); alert("success"); }else{ alert("error"); } }, error : function(){ alert("error"); } }); }) }) </script>
三、后台
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; public class RegisterAction { private String name; private String sex; private String age; public String register() { ActionContext ac = ActionContext.getContext(); HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE); response.setCharacterEncoding("utf-8"); PrintWriter out; try { out = response.getWriter(); JSONObject json=new JSONObject(); json.put("success", true); json.put("name", name); json.put("sex", sex==null?"未知":("1".equals(sex)?"男":"女")); json.put("age", age); out.write(json.toString()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } return null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
四、Struts配置
<struts> <package name="build" extends="struts-default"> <action name="RegisterAction" method="register" class="com.home.RegisterAction"> </action> </package> </struts>
例如以下图:
作者:itmyhome
出处:http://blog.csdn.net/itmyhome1990/article/details/41943291
源代码:download