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:
           
                ${allowedFields}  
           

   But failed.As we know, we can set filename like this when download file

        
            application/octet-stream
            attachment;filename="${filename}"
            1024
        
       
 


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


            

你可能感兴趣的:(json,Struts,hack)