美文网首页
Groovy 执行自定义脚本

Groovy 执行自定义脚本

作者: Tinyspot | 来源:发表于2024-01-08 17:58 被阅读0次

    1. 自定义脚本

    1.1 页面

    1.2 引入依赖

    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>3.0.13</version>
        <type>pom</type>
    </dependency>
    

    2. 页面 script.html

    @Controller
    @RequestMapping("groovy")
    public class GroovyController {
    
        @GetMapping(value = {"", "/script"})
        public ModelAndView script() {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("attr", "value");
            modelAndView.setViewName("script.html");
            return modelAndView;
        }
    }
    
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>script</title>
    
        <style type="text/css">
            .button {
                position: absolute;
                background-color: #0a0a23;
                color: #fff;
                border: none;
                width: 100px;
                border-radius: 2px;
                padding: 5px;
            }
            .button:focus {
                outline-color: transparent;
                outline-style: solid;
                box-shadow: 0 0 0 2px #333338;
            }
        </style>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    </head>
    <body>
    <div class="tool_class">通用工具</div>
    
    <form>
        <div class="form_class">
            <span class="span_class">执行脚本</span>
            <textarea id="script" style="resize:none; width: 500px;" rows="10"></textarea>
        </div>
        <div class="form_class">
            <span class="span_class">调用参数:</span>
            <textarea id="params" style="resize:none; width: 500px;" rows="6"></textarea>
        </div>
        <div class="form_class" id="submitDiv">
            <button id="btn_click" class="button" type="button">提交</button>
        </div>
    </form>
    <script>
        $().ready(function () {
            $("#btn_click").click(function () {
                $('#result').remove();
    
                var script = $("#script").val();
                script = script.replace(/\n/g, " ")
                var params = $("#params").val();
    
                $.ajax({
                    type: "POST",
                    url: "/groovy/execute",
                    data: {
                        script: script,
                        params: params
                    },
                    async: true,
                    dataType: "json",
                    success: function (data) {
                        var startElement = $('#submitDiv');
                        var resultEle = '<div class="result" id="result"> <span class="span_class">执行结果:</span> ' +
                            '<textarea style="resize:none; width: 500px;" rows="10" >' + JSON.stringify(data, null, 4) + '</textarea></div>';
                        startElement.after(resultEle);
                    }
                });
    
            });
        });
    </script>
    </body>
    </html>
    

    3. 执行脚本

    @RestController
    @RequestMapping("/groovy")
    public class GroovyRunController {
    
        /**
         * @param params json串
         */
        @PostMapping("/execute")
        public JSONObject execute(String script, String params) {
            Class<?> clazz = GroovyUtil.parseClass(script);
            Object obj = GroovyUtil.runScript(clazz, SpringBeanUtils.getApplicationContext(), params);
    
            JSONObject result = new JSONObject();
            JSONObject response = new JSONObject();
            response.put("data", obj);
            response.put("success", "true");
            result.put("response", response);
    
            return result;
        }
    }
    
    public class GroovyUtil {
    
        public static Object runScript(Class<?> clazz, ApplicationContext applicationContext, String params) {
            Map<String, Object> groovyParams = new HashMap<>(6);
            groovyParams.put("context", applicationContext);
            groovyParams.put("data", params);
    
            try {
                GroovyObject instance = (GroovyObject) clazz.newInstance();
                Object result = instance.invokeMethod("execute", groovyParams);
                return result;
            } catch (Exception e) {
                return e.getMessage();
            }
        }
    
        public static Class<?> parseClass(String script) {
            GroovyClassLoader classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
            Class<?> clazz = classLoader.parseClass(script);
            return clazz;
        }
    }
    

    脚本内容

    package com.example.concrete.starter.third;
    
    import com.alibaba.fastjson.JSON;
    import com.example.concrete.common.domain.UserDTO;
    import com.example.concrete.starter.service.GreetService;
    import org.springframework.context.ApplicationContext;
    
    import java.util.Map;
    
    public class GreetScript {
    
        public String execute(Map<String, Object> contextMap) {
            ApplicationContext applicationContext = (ApplicationContext) contextMap.get("context");
            String jsonStr = (String) contextMap.get("data");
            UserDTO userDTO = JSON.parseObject(jsonStr, UserDTO.class);
    
            GreetService greetService = (GreetService) applicationContext.getBean("greetServiceImpl");
            return greetService.greeting(userDTO, "groovy-script");
        }
    }
    

    相关文章

      网友评论

          本文标题:Groovy 执行自定义脚本

          本文链接:https://www.haomeiwen.com/subject/ymqondtx.html