struts 2-json-pluginプラグインの使用
3293 ワード
一、アクションを編纂する
/**
* AjaxJsonAction.java
* action
* Function: TODO
*
* version date author
* ──────────────────────────────────
* 1.0 2013-9-21 songjy
*
* Copyright (c) 2013, TNT All Rights Reserved.
*/
package action;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
import entity.User;
/**
* ClassName:AjaxJsonAction
*
* @author songjy
* @version 1.0
* @since v1.0
* @Date 2013-9-21 5:42:49
*/
public class AjaxJsonAction extends ActionSupport {
private static final long serialVersionUID = -2309225335616212699L;
private static Map<Integer, User> users = new HashMap<Integer, User>();
static {
users.put(1, new User(1, " "));
users.put(2, new User(2, " "));
}
public String json(){
if(users.containsKey(id))
user = users.get(id);
else
user = new User();
return "json";
}
private int id;
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/*user getXXX,json User json*/
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
二、struts.xmlにアクションクラスを配置する<!-- json-default, struts2-json-plugin.jar struts-plugin.xml -->
<package name="ajax" extends="json-default">
<action name="*" class="action.AjaxJsonAction" method="{1}">
<result name="{1}" type="json"/><!-- type json -->
</action>
</package>
三、jspページの作成<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<title>struts2-json-plugin </title>
<script type="text/javascript">
function load_user() {
var id = encodeURIComponent($("#id").val());
$.post("json.do", {
id : id
}).done(function(data) {
alert(data.user.id + "," + data.user.name +"," +data.id);
});
}
</script>
</head>
<body>
id:
<input name="id" type="text" id="id">
<br />
<input type="button" onclick="javascript:load_user();" value=" " />
</body>
</html>
、テスト