JSON与 STRuts2

阅读更多

package com.huawei.cmclient.common.config;


import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.huawei.cmclient.common.sys.SystemLoader;
import com.huawei.cmclient.common.utils.ParamChecking;
import com.huawei.cmclient.common.utils.UnifyUtils;
import com.huawei.cmclient.common.vo.tree.Tree;
import com.huawei.cmclient.common.vo.tree.TreeNode;


public class TreeConfig
{

    private static final Map treeMap = new HashMap();

    private String nodeConfigFile;

    public static Map getTreeMap()
    {
        return treeMap;
    }

    /**
     * 读取配置文件
     */
    public void init()
    {
        try
        {
            String cmClientPath = SystemLoader.getCmClientPath();
           // File configFile = new File(cmClientPath + File.separator + nodeConfigFile.trim());
            File configFile = new File("D://我的文档//workspace/CMClient//WebRoot//WEB-INF//conf//common//tree_config.xml");
           
            SAXReader reader = new SAXReader();
            Document document = reader.read(configFile);
            parse(document);

        }
        catch (DocumentException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 解析配置值
     * @param document
     * @throws Exception 抛出异常
     */
    private void parse(Document document)
        throws Exception
    {
        Tree tree = null;
        TreeNode treeNode = null;
        final Element root = document.getRootElement();
        final List< ? > trees = root.elements("tree");
        for (final Iterator< ? > iterator = trees.iterator(); iterator.hasNext();)
        {
            Element treeElement = (Element) iterator.next();

            tree = new Tree();
            parseTreeAttribute(tree, treeElement);

            List< ? > nodes = treeElement.elements("node");
            for (final Iterator< ? > iter = nodes.iterator(); iter.hasNext();)
            {

                final Element nodeElement = (Element) iter.next();
               
                treeNode = new TreeNode();

                parseNodeAttribute(treeNode, nodeElement);
               
                parseNodeValue(treeNode,nodeElement);

                tree.getNodeList().add(treeNode);
            }
            treeMap.put(tree.getId(), tree);
        }
    }

    private void parseTreeAttribute(Tree tree, Element element)
    {

        //
        final Attribute idAtt = element.attribute("id");
        tree.setId("root");
        if (null != idAtt && ParamChecking.isBlank(idAtt.getValue()))
        {
            tree.setId(UnifyUtils.processTrim(idAtt.getValue()));
        }

        final Attribute useArrowsAtt = element.attribute("useArrows");
        if (null != useArrowsAtt && "false".equals(UnifyUtils.processTrim(useArrowsAtt.getValue())))
        {
            tree.getTreeOptions().setUseArrows(false);
        }

    }

    private void parseNodeAttribute(TreeNode node, Element element)
    {
        final Attribute expanded = element.attribute("expanded");
        if (null != expanded && "false".equals(expanded.getValue()))
        {
            node.getTreeNodeOptions().setExpanded(false);
        }

    }

    private void parseNodeValue(TreeNode node, Element element)
    {
        org.dom4j.Node idNode = element.element("id");
        org.dom4j.Node textNode = element.element("text");
        org.dom4j.Node parentIdNode = element.element("parentId");
        org.dom4j.Node methodNode = element.element("method");

        node.setId(idNode.getText().trim());
        node.setParentId(parentIdNode.getText().trim());
        node.setText(textNode.getText().trim());
        node.setMethod(methodNode.getText().trim());
    }

    /**
     * @return Returns the nodeConfigFile.
     */
    public String getNodeConfigFile()
    {
        return nodeConfigFile;
    }

    /**
     * @param nodeConfigFile The nodeConfigFile to set.
     */
    public void setNodeConfigFile(String nodeConfigFile)
    {
        this.nodeConfigFile = nodeConfigFile;
    }

}
=====================================================================


package com.huawei.cmclient.common.action;


import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.rpc.holders.StringHolder;

import localhost.imsservice.services.CentrexService.Centrex;
import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

import com.chinamobile.imsservice.centrex.datatype.holders.IntValueHolder;
import com.huawei.cmclient.common.config.TreeConfig;
import com.huawei.cmclient.common.utils.ParamChecking;
import com.huawei.cmclient.common.vo.tree.Tree;
import com.opensymphony.xwork2.ActionSupport;


public class BaseAction
    extends ActionSupport
{

    private static final long serialVersionUID = 1L;

    private Centrex centrex;

    private boolean success;

    private String msg;

    private String jsonString = "";

    public HttpServletRequest getRequest()
    {
        return ServletActionContext.getRequest();
    }

    public HttpSession getSession()
    {
        return ServletActionContext.getRequest().getSession();
    }

    public ServletContext getApplication()
    {
        return ServletActionContext.getServletContext();
    }

    public HttpServletResponse getResponse()
    {
        return ServletActionContext.getResponse();
    }

    /**
     * @return Returns the centrex.
     */
    public Centrex getCentrex()
    {
        return centrex;
    }

    /**
     * @param centrex The centrex to set.
     */
    public void setCentrex(Centrex centrex)
    {
        this.centrex = centrex;
    }

    public String getJsonString()
    {
        return jsonString;
    }

    public void setJsonString(String jsonString)
    {
        this.jsonString = jsonString;
    }

    public void outJson(String xmlMessage)
    {
        HttpServletResponse response = getResponse();
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
        try
        {
            out = response.getWriter();
            out.write(xmlMessage);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                out.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public StringBuffer getJsonString(String root, Object obj, Map param)
    {
        StringBuffer json = new StringBuffer();
        json.append("{\"success\":" + true + ",\"" + root + "\":");
        JSONArray array = JSONArray.fromObject(obj);
        json.append(array.toString());
        if (!ParamChecking.isEmpty(param))
        {
            for (Entry entity : param.entrySet())
            {
                json.append(",\"");
                json.append(entity.getKey());
                json.append("\":\"");
                json.append(entity.getValue() + "\"");
            }

        }
        json.append("}");
        return json;
    }

    public StringBuffer getJsonString(String[] roots, Object[] objs, Map param)
    {
        StringBuffer json = new StringBuffer();
        json.append("{\"success\":");
        json.append(true);
        for (int i = 0; i < roots.length; i++)
        {
            json.append(",\"");
            json.append(roots[i]);
            json.append("\":");
            json.append(JSONArray.fromObject(objs[i]).toString());
        }

        if (!ParamChecking.isEmpty(param))
        {
            for (Entry entity : param.entrySet())
            {
                json.append(",\"");
                json.append(entity.getKey());
                json.append("\":\"");
                json.append(entity.getValue() + "\"");
            }

        }
        json.append("}");
        return json;
    }

    public String getJsonString(IntValueHolder resultcode, String returnDesc)
    {
        StringBuffer json = new StringBuffer();
        if (resultcode == null || resultcode.value == null || resultcode.value.getValue() == null
            || resultcode.value.getValue() != 0)
        {
            json.append("{\"failure\":" + true + ",\"msg\":\"" + returnDesc.replaceAll("\n", "
"));

        }
        else
        {
            json.append("{\"success\":" + true + ",\"msg\":\"" + returnDesc.replaceAll("\n", "
"));
        }
        json.append("\"}");
        return json.toString();
    }

    public String getJsonOtherErrorString()
    {
        StringBuffer json = new StringBuffer();
        json.append("{\"failure\":" + true + ",\"msg\":\"" + "其它错误");
        json.append("\"}");
        return json.toString();
    }

    /**处理服务端的返回消息
     * @param resultCode
     * @param resultDesc
     * @see
     */
    public void processResult(IntValueHolder resultCode, StringHolder resultDesc)
    {
        this.success = true;
        if (null == resultCode || null == resultCode.value || resultCode.value.getValue() != 0)
        {
            this.success = false;
        }
        this.msg = "     操作失败!      ";//修改返回成功消息时,IE6界面显示不全的问题,modi by zhouchen 2011-07-18
        if (null != resultDesc && !ParamChecking.isBlank(resultDesc.value))
        {
            //修改返回成功消息时,IE6界面显示不全的问题,modi by zhouchen 2011-07-08
            Map paramMap = new HashMap();
            StringBuffer sBuffer = new StringBuffer();
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(resultDesc.value);
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            paramMap.put("resultDesc", sBuffer.toString());
            String resultdesc = sBuffer.toString();
            this.msg = resultdesc.replaceAll("\n", "
       ");//modi by zhouchen 将回车换行符修改成空格 2011-7-12
        }

    }
   
    /**处理服务端的返回消息
     * @param resultCode
     * @param resultDesc
     * @see
     */
    public void processResultOneNumber(IntValueHolder resultCode, StringHolder resultDesc)
    {
        this.success = true;
        if (null == resultCode || null == resultCode.value || resultCode.value.getValue() != 110000)
        {
            this.success = false;
        }
        this.msg = "     操作失败!      ";//修改返回成功消息时,IE6界面显示不全的问题,modi by zhouchen 2011-07-18
        if (null != resultDesc && !ParamChecking.isBlank(resultDesc.value))
        {
            //修改返回成功消息时,IE6界面显示不全的问题,modi by zhouchen 2011-07-08
            Map paramMap = new HashMap();
            StringBuffer sBuffer = new StringBuffer();
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(resultDesc.value);
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            sBuffer.append(" ");
            paramMap.put("resultDesc", sBuffer.toString());
            String resultdesc = sBuffer.toString();
            this.msg = resultdesc.replaceAll("\n", "
       ");//modi by zhouchen 将回车换行符修改成空格 2011-7-12
        }

    }

    /**
     * 获取工程的绝对路径
     * @return String "http://ip:port/CMServer/"
     * @see
     */
    public String getUrl()
    {
        String http = getRequest().getScheme();
        String ip = getRequest().getLocalAddr();
        String contextPath = getRequest().getContextPath();
        int port = getRequest().getServerPort();

        StringBuffer urlStr = new StringBuffer();
        urlStr.append(http).append("://").append(ip).append(":").append(port).append(contextPath)
            .append("/");//File.separator

        return urlStr.toString();
    }

    /**
     * @return Returns the success.
     */
    public boolean isSuccess()
    {
        return success;
    }

    /**
     * @param success The success to set.
     */
    public void setSuccess(boolean success)
    {
        this.success = success;
    }

    /**
     * @return Returns the msg.
     */
    public String getMsg()
    {
        return msg;
    }

    /**
     * @param msg The msg to set.
     */
    public void setMsg(String msg)
    {
        this.msg = msg;
    }
   
    public static void main(String[] args)
    {
        BaseAction base=new BaseAction();
        TreeConfig config=new TreeConfig();
        config.init();
        Tree tree = TreeConfig.getTreeMap().get("root");
        StringBuffer jsonBuffer = base.getJsonString("root", tree, null);
       
        System.out.println(jsonBuffer);
    }

}
===========================================================
public String init()
    {
        //如果没有登录,返回登录页面
        Object userKey = super.getSession().getAttribute(LoginContext.USERKEY);
        if (null == userKey)
        {
            return ERROR;
        }
        Tree tree = TreeConfig.getTreeMap().get("root");
        StringBuffer jsonBuffer = super.getJsonString("root", tree, null);
        super.getRequest().setAttribute("treeRoot", jsonBuffer.toString());
        return SUCCESS;
    }
==================================================

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">



class="TeamServiceAction">

false
success,msg



class="TeamServiceAction">

false
success,msg



class="TeamServiceAction">

false
success,msg



class="TeamServiceAction">

false

success,msg,groupID,groupNumber,serviceTeamsResp.*




class="TeamServiceAction">

false
success,msg



class="TeamServiceAction">

false
success,msg



class="TeamServiceAction">

false

success,msg,groupNumber,teamId,leftDisabled,rightDisabled,teamUsersResp.*






你可能感兴趣的:(json)