论坛首页 Java企业应用论坛

Hack struts2 json plugin: dynamically set includeProperty

浏览 2319 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-07-26  
  Here is not basic use of struts2 json plugin but how to hack the code to set includeProperty dynamically, in othter words, set with action field not in xml file.
 
  Train of thought:
  I have a demand of changing includeParameter values when different ip request, I wonder whether I could set like this:
         <result type="json">  
                <param name="includeParameter">${allowedFields}</param>  
         </result>  

   But failed.As we know, we can set filename lick this when download file
<action name="download" class="action.DownloadAction">
        <result name="success" type="stream">
            <param name="contentType">application/octet-stream</param>
            <param name="contentDisposition">attachment;filename="${filename}"</param>
            <param name="bufferSize">1024</param>
        </result>
       
</action> 


do the hack:
    I try to find out the different between json plugin and download plugin and find the way out to copy the ability.
    Extend the json result class, add conditionalParse function, and filter in execute function.
public class JSONDynamicResult extends JSONResult {
    protected String conditionalParse(String param, ActionInvocation invocation) {
      
            return TextParseUtil.translateVariables(param, invocation.getStack(),
                    new TextParseUtil.ParsedValueEvaluator() {
                        public Object evaluate(Object parsedValue) {
                           
                            return parsedValue;
                        }
            });
       
    }

    public void execute(ActionInvocation invocation)
        throws Exception
    {
        ActionContext actionContext = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest)actionContext.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");
        HttpServletResponse response = (HttpServletResponse)actionContext.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
        // fake code here, you shoud use a field to get "${allowedFields}" and test empty to compatible to origin use
        setIncludeProperty(conditionalParse("${allowedFields}",invocation));

        try
        {
            Object rootObject = readRootObject(invocation);
            writeToResponse(response, createJSONString(request, rootObject), enableGzip(request));
        }
        catch(IOException exception)
        {
            LOG.error(exception.getMessage(), exception, new String[0]);
            throw exception;
        }
    }

}



last set the result class

<result-types>
            <result-type name="json" class="your.parckage.JSONDynamicResult "/>
</result-types>

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics