繁体   English   中英

如何将执行的 GROOVY 脚本结果返回到 REST API 响应

[英]How to return executed GROOVY script results to REST API Response

I am working to develop an REST API in spring boot that will accept any groovy script in request body and will execute it on server and return the executed results. 我试图找出如何获得脚本的执行结果,即使脚本明确没有返回任何值。 这就像一个在线 groovy 编译器,您可以在其中发布代码并获得结果

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

public class GroovyController {
public static void main(String[] args) throws ScriptException {

   System.out.println(runScript());

}


public static String runScript(){
    String script = "class Student {\n" +
            "   private int StudentID;\n" +
            "   private String StudentName;\n" +
            "\t\n" +
            "   void setStudentID(int pID) {\n" +
            "      StudentID = pID;\n" +
            "   }\n" +
            "\t\n" +
            "   void setStudentName(String pName) {\n" +
            "      StudentName = pName;\n" +
            "   }\n" +
            "\t\n" +
            "   int getStudentID() {\n" +
            "      return this.StudentID;\n" +
            "   }\n" +
            "\t\n" +
            "   String getStudentName() {\n" +
            "      return this.StudentName;\n" +
            "   }\n" +
            "\t\n" +
            "   static void main(String[] args) {\n" +
            "      Student st = new Student();\n" +
            "      st.setStudentID(1);\n" +
            "      st.setStudentName(\"Joe\");\n" +
            "\t\t\n" +
            "      println(st.getStudentID());\n" +
            "      println(st.getStudentName());\n" +
            "   } \n" +
            "}";


    GroovyShell shell = new GroovyShell();

    Object result = shell.evaluate(script);
    return result.toString();

}

}

我已经弄清楚了如何在安全沙箱 model 中使用 java 运行 groovy 脚本。 I used run method of Groovy Shell class to run the groovy scripts with java. 如果执行的脚本本身返回任何值,例如return 2 * 4将返回 4,并且如果脚本没有任何 return 语句并且 shell 的 run 方法将返回 null,则 Run 方法返回结果。

println("Hello world!!")的情况下,它不会明显返回任何内容,但在 API 的请求负载中发送此脚本的客户端会期望打印文本作为响应。 要捕获 PrintStream 写入的内容,可以使用绑定将自定义 PrintWriter 绑定到 GroovyShell 中的 object。 I had written a complete Spring Boot based Micro Service which exposes a REST API to execute Groovy Scripts on.the server in a secured sandbox model.

完整的微服务代码可以在这里找到脚本执行服务

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM