vulcan

          低頭做事,抬頭看路

             :: 首頁 :: 聯系 :: 聚合  :: 管理
            41 Posts :: 7 Stories :: 28 Comments :: 0 Trackbacks

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

            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 閱讀(2243) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 枣强县| 思茅市| 长武县| 锡林浩特市| 舟曲县| 会泽县| 昌平区| 公主岭市| 青龙| 洪泽县| 泉州市| 宁远县| 陇川县| 莎车县| 鄯善县| 克山县| 温州市| 沁源县| 阿克陶县| 贡山| 富宁县| 洛宁县| 饶河县| 陇南市| 新宁县| 吉林省| 丰宁| 洛宁县| 金秀| 浙江省| 万源市| 大丰市| 新乡市| 克东县| 城市| 曲沃县| 上饶县| 郴州市| 德江县| 从江县| 禄丰县|