vulcan

          低頭做事,抬頭看路

             :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            41 Posts :: 7 Stories :: 28 Comments :: 0 Trackbacks

          在JSON.org上看到j(luò)ava實(shí)現(xiàn)的源碼,想著自己寫一個(gè)Result支持JSON的返回,但是一看webwork的新版本2.2.7版本已經(jīng)支持JSON了
          ,但是有bug,第一,jsonObjectProperty的setter方法寫成了setJSONObjectProperty所以,在配置中若使用了jsonObjectProperty做為參數(shù)名,那么是不能set參數(shù)進(jìn)去的。另外,它不支持自定義返回js的編碼,造成亂碼,或者干脆都無法正常調(diào)用js,還有就是我覺得可以再封裝得好一點(diǎn),對(duì)于JSONObject的生成,可以利用反射來做,而不是在每個(gè)Action中都手工的寫生成JSONObject的代碼,所以我做了一下改進(jìn):

            1package com.csair.hunan.common.web;
            2
            3import java.io.OutputStream;
            4import java.lang.reflect.Field;
            5
            6import javax.servlet.http.HttpServletResponse;
            7
            8import org.apache.commons.logging.Log;
            9import org.apache.commons.logging.LogFactory;
           10import org.json.JSONObject;
           11
           12import com.opensymphony.webwork.ServletActionContext;
           13import com.opensymphony.webwork.WebWorkException;
           14import com.opensymphony.xwork.ActionContext;
           15import com.opensymphony.xwork.ActionInvocation;
           16import com.opensymphony.xwork.Result;
           17
           18public class JSONResult implements Result {
           19
           20    private static final Log LOG = LogFactory.getLog(JSONResult.class);
           21
           22    private String jsonObjectProperty = "jsonObject";
           23    private String contentType = "application/json";
           24    private String encoding = "utf-8";
           25
           26    public void setEncoding(String encoding) {
           27        this.encoding = encoding;
           28    }

           29    /**
           30     * Returns the property which will be used to lookup {@link JSONObject} in WebWork's ValueStack. Default to
           31     * 'jsonObject'.
           32     *
           33     * @return String
           34     */

           35
           36    public String getJsonObjectProperty() {
           37        return jsonObjectProperty;
           38    }

           39    /**
           40     * Set the property which will be used to lookup {@link JSONObject} in WebWork's ValueStack. Default to
           41     * 'jsonObject'.
           42     * 
           43     * @param jsonObject
           44     */

           45
           46    public void setJsonObjectProperty(String jsonObjectProperty) {
           47        this.jsonObjectProperty = jsonObjectProperty;
           48    }

           49
           50    /**
           51     * Returns the content-type header to be used. Default to 'application/json'.
           52     * 
           53     * @return String
           54     */

           55    public String getContentType() {
           56        return contentType;
           57    }

           58
           59    /**
           60     * Set the content-type header to be used. Default to 'application/json'.
           61     * 
           62     * @param contentType
           63     */

           64    public void setContentType(String contentType) {
           65        this.contentType = contentType;
           66    }

           67
           68
           69    /**
           70     * Writes the string representation of {@link JSONObject} defined through {@link #getJSONObjectProperty()}
           71     * to {@link javax.servlet.http.HttpServletResponse}'s outputstream. 
           72     *
           73     * @param invocation
           74     * @throws Exception
           75     */

           76    public void execute(ActionInvocation invocation) throws Exception {
           77
           78        if (LOG.isDebugEnabled()) {
           79            LOG.debug("executing JSONResult");
           80        }

           81
           82        JSONObject jsonObject = getJSONObject(invocation);
           83        if (jsonObject != null{
           84            String json = jsonObject.toString();
           85            HttpServletResponse response = getServletResponse(invocation);
           86            response.setContentType(getContentType());
           87            //encoding 
           88            byte[] bs = json.getBytes(this.encoding);
           89            response.setContentLength(bs.length);
           90
           91            OutputStream os = response.getOutputStream();
           92            os.write(bs);
           93            os.flush();
           94
           95            if (LOG.isDebugEnabled()) {
           96                LOG.debug("written ["+json+"] to HttpServletResponse outputstream");
           97            }

           98        }

           99    }

          100
          101    /**
          102     * Attempt to look up a {@link com.opensymphony.webwork.dispatcher.json.JSONObject} instance through the property
          103     * ({@link #getJSONObjectProperty()}) by looking up the property in WebWork's ValueStack. It shall be found if there's
          104     * accessor method for the property in WebWork's action itself.
          105     * <p/>
          106     * Returns null if one cannot be found.
          107     * <p/>
          108     * We could override this method to return the desired JSONObject when writing testcases.
          109     *
          110     * @param invocation
          111     * @return {@link JSONObject} or null if one cannot be found
          112     */

          113    protected JSONObject getJSONObject(ActionInvocation invocation) throws Exception {
          114        ActionContext actionContext = invocation.getInvocationContext();
          115        Object obj = actionContext.getValueStack().findValue(jsonObjectProperty);
          116
          117
          118        if (obj == null{
          119            LOG.error("property ["+ jsonObjectProperty +"] returns null, expecting JSONObject"new WebWorkException());
          120            return null;
          121        }

          122        //if the assigned object is not an instance of JSONObject, try to build one use reflection
          123        if (! JSONObject.class.isInstance(obj)) {
          124            LOG.warn("property ["+ jsonObjectProperty +"] is ["+obj+"] especting an instance of JSONObject"new WebWorkException());
          125            LOG.debug("build json object by reflection.");
          126            JSONObject jsonObj = new JSONObject();
          127            for (Field field : obj.getClass().getDeclaredFields()) {
          128                String getter = "get" + Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1);
          129                jsonObj.append(field.getName(), obj.getClass().getDeclaredMethod(getter).invoke(obj));
          130            }

          131            return jsonObj;
          132        }

          133        
          134        return (JSONObject) obj;
          135    }

          136
          137
          138    /**
          139     * Returns a {@link javax.servlet.http.HttpServletResponse} by looking it up through WebWork's ActionContext Map.
          140     * </p>
          141     * We could override this method to return the desired Mock HttpServletResponse when writing testcases.
          142     * 
          143     * @param invocation
          144     * @return {@link javax.servlet.http.HttpServletResponse}
          145     */

          146    protected HttpServletResponse getServletResponse(ActionInvocation invocation) {
          147        return (HttpServletResponse) invocation.getInvocationContext().getContextMap().get(ServletActionContext.HTTP_RESPONSE);
          148    }

          149}

          150
          posted on 2008-05-23 16:47 vulcan 閱讀(2244) 評(píng)論(0)  編輯  收藏

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 屯昌县| 赞皇县| 连州市| 库尔勒市| 孟村| 天津市| 临朐县| 隆尧县| 桐梓县| 昌江| 宁波市| 休宁县| 建始县| 张家界市| 娱乐| 蓬安县| 沅陵县| 宣城市| 青冈县| 镇原县| 甘谷县| 万山特区| 阳西县| 洞头县| 合阳县| 夹江县| 山东省| 平泉县| 合江县| 英超| 德庆县| 金平| 金溪县| 贵州省| 项城市| 赤水市| 河间市| 石嘴山市| 南城县| 都昌县| 镇平县|