`

Hack struts2 json plugin: dynamically set includeProperty

阅读更多
  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 like 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>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics