附件中 是 整个项目 ,下载即可使用
1.需要建立数据库和表结构 sql 和数据脚本 见上面
2.讲项目放在TOMCat 可以直接运行
对于前台接收json字符串 的一个思考(2010.05.23):
对于上面的例子,我们是使用 menu.jsp 来接收后台的返回的json字符串
menu.jsp 的内容很简单 2行
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:property value="menuString" escape="false"/>
其中:
<s:property>标签的escape属性默认值为true,即不解析html代码,直接将其输出。
如:novel.NTitle的值为
<font color=red>邪门</font>
则<s:property value="#novel.NTitle">就直接输出原值。若想让标签解析html标签输出:
邪门
则将escape设为false
<s:property value="#novel.NTitle" escape="false"/>
这个例子中我们希望 输出解析后的值,不想看到html标签
<action name="menus" class="cn.com.xinli.tree.action.QueryNodeAction">
<result name="success">/menu.jsp</result>
</action>
并且使用的是 <package name="struts2" extends="struts-default">
我们把 后台的json字符串放在了 menuString 字符串中,
而extends="struts-default" 下面的action 都是页面跳转的意思
<result name="success">/menu.jsp</result>
的意思就是 action执行后 跳转到 menu.jsp
而
tree.loader.dataUrl='http://localhost:9090/struts2/menus!loadTree.action?pid='+node.id
是ext 中的方法 他是用来接受json字符串的 ,首先看看 tree.loader.dataUrl 的源码,可见
tree.loader.dataUrl 是一个ajax请求 接受返回结果,而loadTree.action 返回一个json字符串,刚好绑定在
menu.jsp 中,因此 tree.loader.dataUrl 得到了json字符串,由于是ajax请求,也不会引起页面跳转
- requestData : function(node, callback){
- if(this.fireEvent("beforeload", this, node, callback) !== false){
- this.transId = Ext.Ajax.request({
- method:this.requestMethod,
- url: this.dataUrl||this.url,
- success: this.handleResponse,
- failure: this.handleFailure,
- scope: this,
- argument: {callback: callback, node: node},
- params: this.getParams(node)
- });
- }else{
- // if the load is cancelled, make sure we notify
- // the node that we are done
- if(typeof callback == "function"){
- callback();
- }
requestData : function(node, callback){ if(this.fireEvent("beforeload", this, node, callback) !== false){ this.transId = Ext.Ajax.request({ method:this.requestMethod, url: this.dataUrl||this.url, success: this.handleResponse, failure: this.handleFailure, scope: this, argument: {callback: callback, node: node}, params: this.getParams(node) }); }else{ // if the load is cancelled, make sure we notify // the node that we are done if(typeof callback == "function"){ callback(); }
这种从后台得到 json 字符串,传递到前台一个Jsp页面的做法有点 臃肿,比如我们还需要在 action中 使用json.jar
使用下面的方法 将一个对象转化为 json 字符串
JSONArray jsonObject = JSONArray.fromObject(menus);
menuString = jsonObject.toString();
其实 strtus2已经为我们提供了action 返回 json字符串的支持,下面我们改造 以前手工得到json字符,用一个Jsp页面来接受的例子,换成 使用strtus2 json 插件支持
步骤:
1.首先在以前的项目中加入
jsonplugin-0.32.jar
2. 修改 后台构造Json串的方法
- package cn.com.xinli.tree.action;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.log4j.Logger;
- import cn.com.xinli.tree.bean.FuctionTreeNode;
- import cn.com.xinli.tree.dao.FuctionTreeDao;
- import cn.com.xinli.tree.dao.impl.FuctionTreeDaoImpl;
- public class QueryNodeAction extends BaseAction
- {
- private Logger log=Logger.getLogger(QueryNodeAction.class);
- private String menuString;
- /*返回给前台树的Json 对象,使用struts2 json插件可以直接将这个对象转换为
- * json字符串
- * 需要在struts.xml中进行配置
- *
- * */
- private List<FuctionTreeNode> menusList;
- public List<FuctionTreeNode> getMenusList() {
- return menusList;
- }
- public void setMenusList(List<FuctionTreeNode> menusList) {
- this.menusList = menusList;
- }
- public String getMenuString() {
- return menuString;
- }
- public void setMenuString(String menuString) {
- this.menuString = menuString;
- }
- /*异步加载树*/
- public String loadTree()
- {
- log.info("开始根据父亲节点查找孩子节点");
- HttpServletRequest request=getRequest();
- String nodeId=request.getParameter("pid");
- log.info("父亲节点的ID是:"+nodeId);
- FuctionTreeDao treeDao=new FuctionTreeDaoImpl();
- try
- {
- menusList=treeDao.queryNodeById(nodeId);
- log.info("孩子结点的数目是:"+menusList.size());
- //以下三行代码可以让返回的JSON数据不包含需要过滤的字段
- /*
- JsonConfig config = new JsonConfig();
- //过滤cls属性
- config.setExcludes( new String[]{"cls"});
- JSONArray jsonObject2 = JSONArray.fromObject(menus,config);
- */
- //JSONArray jsonObject = JSONArray.fromObject(menus);
- // menuString = jsonObject.toString();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- return "success";
- }
- /*ajax 调用,返回json 字符串*/
- public String ajax()
- {
- //HttpServletResponse resp= getResponse();
- //resp.setContentType("application/json;charset=UTF-8");
- HttpServletRequest req= getRequest();
- try
- {
- System.out.println("从前台Ajax请求参数是:"+req.getParameter("foo"));
- menuString="[{success:true,msg:'修改权限成功'}]";
- //resp.getWriter().write("{success:true,msg:'修改权限成功'}");
- }
- catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return "aa";
- }
- }
package cn.com.xinli.tree.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import cn.com.xinli.tree.bean.FuctionTreeNode; import cn.com.xinli.tree.dao.FuctionTreeDao; import cn.com.xinli.tree.dao.impl.FuctionTreeDaoImpl; public class QueryNodeAction extends BaseAction { private Logger log=Logger.getLogger(QueryNodeAction.class); private String menuString; /*返回给前台树的Json 对象,使用struts2 json插件可以直接将这个对象转换为 * json字符串 * 需要在struts.xml中进行配置 * * */ private List<FuctionTreeNode> menusList; public List<FuctionTreeNode> getMenusList() { return menusList; } public void setMenusList(List<FuctionTreeNode> menusList) { this.menusList = menusList; } public String getMenuString() { return menuString; } public void setMenuString(String menuString) { this.menuString = menuString; } /*异步加载树*/ public String loadTree() { log.info("开始根据父亲节点查找孩子节点"); HttpServletRequest request=getRequest(); String nodeId=request.getParameter("pid"); log.info("父亲节点的ID是:"+nodeId); FuctionTreeDao treeDao=new FuctionTreeDaoImpl(); try { menusList=treeDao.queryNodeById(nodeId); log.info("孩子结点的数目是:"+menusList.size()); //以下三行代码可以让返回的JSON数据不包含需要过滤的字段 /* JsonConfig config = new JsonConfig(); //过滤cls属性 config.setExcludes( new String[]{"cls"}); JSONArray jsonObject2 = JSONArray.fromObject(menus,config); */ //JSONArray jsonObject = JSONArray.fromObject(menus); // menuString = jsonObject.toString(); } catch (Exception e) { e.printStackTrace(); } return "success"; } /*ajax 调用,返回json 字符串*/ public String ajax() { //HttpServletResponse resp= getResponse(); //resp.setContentType("application/json;charset=UTF-8"); HttpServletRequest req= getRequest(); try { System.out.println("从前台Ajax请求参数是:"+req.getParameter("foo")); menuString="[{success:true,msg:'修改权限成功'}]"; //resp.getWriter().write("{success:true,msg:'修改权限成功'}"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "aa"; } }
3 .修改 struts.xml 关键是 修改 packega 的 extends="json-default"
- <?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="struts2" extends="json-default">
- <action name="login" class="cn.com.xinli.tree.action.LoginAction">
- <result name="success">/result.jsp</result>
- <result name="input">/login2.jsp</result>
- <result name="error">/login2.jsp</result>
- </action>
- <action name="menus" class="cn.com.xinli.tree.action.QueryNodeAction">
- <result name="success" type="json">
- <param name="root">menusList</param>
- </result>
- <result name="aa" type="json">
- <param name="root">menuString</param>
- </result>
- </action>
- </package>
- </struts>
<?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="struts2" extends="json-default"> <action name="login" class="cn.com.xinli.tree.action.LoginAction"> <result name="success">/result.jsp</result> <result name="input">/login2.jsp</result> <result name="error">/login2.jsp</result> </action> <action name="menus" class="cn.com.xinli.tree.action.QueryNodeAction"> <result name="success" type="json"> <param name="root">menusList</param> </result> <result name="aa" type="json"> <param name="root">menuString</param> </result> </action> </package> </struts>
其中
<result name="success" type="json">
<param name="root">menusList</param>
</result>
代表 这个action的返回结果是 json字符串, 其中json串的 root节点 为 menusList
如果你返回的对象 不需要那个属性 可以这么写,则格式化 page 对象为json字符串的时候
conditions,limit,start,success,objCondition 几个属性将被忽略
<param name="root">page</param>
<param name="excludeProperties">
conditions,limit,start,success,objCondition
</param>
相反的 如果只需要对象的 某个属性转化为Json串 可以这么写
<result type="json">
<param name="includeProperties">
success,msg
</param>
</result>
附件中 extTreeJSON.rar 为修改以后例子 ,其中 依赖的Lib 可以下载 以前的lib
- extTree.war (6.5 MB)
- data.rar (652 Bytes)
- extTreeJSON.rar (539.3 KB)