Structs2 Json Ajax实现
1.建立my.struts2.web.JSONResult(自定义结果类,只要实现com.opensymphony.xwork2.Result接口)
package my.struts2.web;
import java.io.PrintWriter;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;
import net.sf.json.JSONArray;
public class JSONResult implements Result{
@Override
public void execute(ActionInvocation invocation) {
try {
ServletActionContext.getResponse().setContentType("text/plain");
PrintWriter responseStream = ServletActionContext.getResponse().getWriter();
ValueStack valueStack = invocation.getStack();
Object jsonModel = valueStack.findValue("jsonModel");
responseStream.println(JSONArray.fromObject(jsonModel));
} catch (Exception e) {
System.out.println(e);
}
}
}
2.structs2 XML配置
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml"/>
<package name="tutorial" extends="struts-default" >
<result-types>
<result-type name="jsonResult" class="my.struts2.web.JSONResult"/> </result-types>
<default-interceptor-ref name="defaultStack"/>
<action name="ajaxTest" class="my.struts2.web.AjaxTestAction">
<result type="jsonResult"/> </action>
</package>
</struts>
3.建立my.struts2.web.AjaxTestAction类
package my.struts2.web;
import com.opensymphony.xwork2.ActionSupport;
public class AjaxTestAction extends ActionSupport{
public String execute() {
User user = new User();
user.setName("huatu122");
user.setPs("xxxxxx");
setJsonModel(user);
return "success";
}
private Object jsonModel;
public Object getJsonModel() {
return jsonModel;
}
public void setJsonModel(Object jsonModel) {
this.jsonModel = jsonModel;
}
}
4.建立my.struts2.web.User
package my.struts2.web;
public class User {
private String name;
private String ps;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPs() {
return ps;
}
public void setPs(String ps) {
this.ps = ps;
}
}
5.建立ajaxTest.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Structs2 AjaxTest</title>
<script type="text/javascript">
function ajaxResponse(){
if(req.readyState==4){
var myObject = eval('(' + req.responseText + ')');
alert("name:"+myObject[0].name);
alert("ps:"+myObject[0].ps);
}
}
function ajaxPost(callback, url) {
if (window.XMLHttpR