前提: springMVC项目已搭建好。
模拟:前台调后台Controller--->service---->groovy文件--->返回或者操作业务
创建处理Groovy的公用类
里面的存放groovy文件的地址可以改变,现在设为:C盘根目录
package com.gybr.util;
import groovy.lang.Binding;
import groovy.lang.GroovyObject;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import java.io.IOException;
public class GroovyCommonUtil {
static String root[]=new String[]{"C:\\"};
static GroovyScriptEngine groovyScriptEngine;
static{
try {
groovyScriptEngine=new GroovyScriptEngine(root);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 用于调用指定Groovy脚本中的指定方法
* @param scriptName 脚本名称
* @param methodName 方法名称
* @param params 方法参数
* @return
*/
@SuppressWarnings({ "rawtypes"})
public static Object invokeMethod(String scriptName, String methodName, Object... params){
Object ret = null;
Class scriptClass = null;
GroovyObject scriptInstance = null;
try {
scriptClass = groovyScriptEngine.loadScriptByName(scriptName);
scriptInstance = (GroovyObject)scriptClass.newInstance();
} catch (ResourceException | ScriptException | InstantiationException | IllegalAccessException e1) {
e1.printStackTrace();//此处应输出日志
}
try {
ret = (String)scriptInstance.invokeMethod(methodName, params);
} catch (IllegalArgumentException | SecurityException e) {
e.printStackTrace();//此处应输出日志
}
return ret;
}
/**
* 用于调用指定Groovy脚本 无方法
* @param fileName groovy文件名
* @param binding binding对象
* @return
*/
public static Object getNoFunctionGroovy(String fileName, Binding binding){
// GroovyScriptEngine engine;
try {
// engine = new GroovyScriptEngine("C:\\");
Object obj =groovyScriptEngine.run( fileName , binding);
System.out.println(binding.getVariable("show"));//获取groovy 的binding中值
System.out.println(binding.getVariable("show1"));//获取 不加def的值
//remove repeate key
// binding.getVariables();
return obj;
} catch (ResourceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
项目的controller层
package com.gybr.web;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gybr.service.TUserManager;
@Controller
@RequestMapping(value = "/user")
public class TUserController {
private TUserManager tUserManager;
@Autowired
public void settUserManager(TUserManager tUserManager) {
this.tUserManager = tUserManager;
}
@RequestMapping(value = {"groovy", ""})
public void groovy(Model model,HttpServletRequest request,HttpServletResponse response) {
PrintWriter out;
try {
out = response.getWriter();
String str=tUserManager.TGroovy1();
out.println(str);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
项目的service层
package com.gybr.service;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.gybr.dao.TUserDao;
import com.gybr.entity.TUser;
import com.gybr.util.GroovyCommonUtil;
@Component
@Transactional
public class TUserManager {
private TUserDao tUserDao;
@PersistenceContext
private EntityManager entityManager;
@Autowired
public void settUserDao(TUserDao tUserDao) {
this.tUserDao = tUserDao;
}
public TUser getTUser(Long id) {
return tUserDao.findOne(id);
}
public List<TUser> getTUserList(){
return (List<TUser>) tUserDao.findAll();
}
@Transactional(readOnly = false)
public void saveTUser(TUser entity) {
if (entity.getUid() == null) {
entity.setName("155555");
entity.setSex("男");
}
tUserDao.save(entity);
}
public String TGroovy1(){
Binding binding = new Binding();
binding.setVariable( "world" , "Fatedgar" );
binding.setVariable( "hi" , " 你好!" );
TUser tUser=new TUser();
tUser.setName("fatedgar");
tUser.setSex("男");
binding.setVariable( "tu" , tUser );
binding.setVariable( "entityManager" , entityManager );
String result = (String)GroovyCommonUtil.getNoFunctionGroovy("Test.groovy", binding);
return result;
}
public String TGroovy2(){
String result = (String)GroovyCommonUtil.invokeMethod("hello.groovy", "helloWithoutParam");
System.out.println("testGroovy2: " + result + "\n");
return result;
}
public String TGroovy3(){
TUser tUser = new TUser();
tUser.setName("fatedgar");
tUser.setSex("男");
String result = (String)GroovyCommonUtil.invokeMethod("hello.groovy", "helloWithParam", tUser, "testGroovy4");
System.out.println("testGroovy3: " + result + "\n");
return result;
}
public String TGroovy4(){
// TUser tUser = new TUser();
// tUser.setName("fatedgar");
// tUser.setSex("男");
String result = (String)GroovyCommonUtil.invokeMethod("hello.groovy", "helloWithDao", tUserDao, 2);
System.out.println("testGroovy4: " + result + "\n");
return result;
}
public String TGroovy5(){
// TUser user=new TUser();
// user.setName("eeee");
// user.setSex("fff");
// entityManager.persist(user);
// return "";
String result = (String)GroovyCommonUtil.invokeMethod("hello.groovy", "helloWithEntity", entityManager,Long.parseLong("1"));
System.out.println("testGroovy5: " + result + "\n");
return result;
}
}
groovy文件存放在C盘根目录
Test.Groovy
import com.gybr.entity.TUser;
def hw = "Hello, ${world}!"
def str="fatedgar ${hi}"
//获取传过来的TUser对象
def ss=binding.variables.tu;
//获取传过来的EntityManager对象
def entityManager=binding.variables.entityManager;
def show="得到了我……"
binding.setVariable( "show" , show);//java接收可以从binding中取值
println hw+"This is my frist groovy demo"
show1="fffff";//类似 binding.setVariable( "show1" , "fffff");
def t=new TUser(name:'张三',sex:'男');
entityManager.persist(t);//保存数据库
return "|"+hw+"||"+str+"||" +ss.name +"|"+ss.getSex()
hello.groovy
package com.gybr.service;
import com.gybr.entity.TUser;
import com.gybr.entity.LeaveJpaEntity;
def helloWithoutParam(){
println "start to call helloWithoutParam!"
return "success, helloWithoutParam";
}
def helloWithParam(tUser, id){
println "start to call helloWithParam, param{person:" + tUser + ", id:" + id + "}";
return "success, hello-1--|"+tUser.name+"|"+tUser.getSex();
}
def helloWithDao(def tUserDao,def id){
def t=tUserDao.findOne(id)
return t.name+"||||"+t.sex;
}
def helloWithEntity(def entityManager,def id){
def t=new TUser(name:'张三',sex:'ffff');
entityManager.persist(t);
def l=entityManager.find(LeaveJpaEntity.class, id);
return l.reason;
}
输入访问路径:
http://localhost:8080/AG/user/groovy
即可显示效果。
注:整个工程中嵌入activiti,还在调试中 以后在activiti博客中上传
分享到:
相关推荐
Java调用Groovy,实时动态加载数据库groovy脚本,java读取mongoDB的groovy脚本,加载实时运行,热部署
Groovy 调用 Java 类groovy 调用 Java class 十分方便,只需要在类前导入该 Java 类,在 Groovy 代码中就可以无缝使用该
SpringBoot-Gradle-Maven-Java-Groovy:SpringBoot通过不同构建工具和语言实现。
Making Java Groovy is a practical handbook for developers who want to blend Groovy into their day to day work with Java It starts by introducing the key differences between Java and Groovy and how you...
Java中使用Groovy的三种方式,详细见我的博客。
Spock 是适合 Java 和 Groovy 应用程序的一个测试框架
java嵌入groovy所需jar 2.3.7最新版
干货:Jenkins Pipeline调用shell、python、java、groovy脚本的正确使用姿势.doc
JGSK, Java,Groovy,Scala,Kotlin 四种语言的特点对比
Making Java Groovy Kenneth A. Kousen 1.Easier Java 2.Closures, builders, and metaprogramming 3.Gradle for builds, Spock for testing 4.Groovy frameworks like Grails and Griffon 源码
Making Java Groovy--Kenneth.A.Kousen. Java Groovy 很不错的学习资料
Groovy环境搭建教程中的例子工程,纯Java、纯Groovy以及Java+Groovy混合 教程参考:http://blog.csdn.net/rcom10002/archive/2011/06/26/6568557.aspx
概述主要介绍Java、spring与groovy结合使用,高清英文版本
姿势需要解锁,不学习怎么会? 老司机开个车,java和groovy都是比较实用的。python用的但是也是可以的
maven3-junit-spock-testng-mixin Maven3示例项目,用于同时执行TestNG(Java,Groovy)+ JUnit(Java,Groovy)+ Spock(Groovy)测试用例。 对于Gradle用户,请参阅 mvn -version: Apache Maven 3.3.9 (bb52d...
Making Java Groovy
java运行groovy 环境,搭建方便自己练习groovy使用 与后续定时调度动态代码做准备
java 动态脚本语言 精通 Groovy
java、groovy、C#、Javascript的运行效率到底如何? 通过实验比较,Javascript的运行效率解决java,看来基于javascript的html5前途远大。 C#的Release版的运行性能也相当高,和C++相差不大,值得推荐。 文件内部...
NULL 博文链接:https://yangwencan2002.iteye.com/blog/260697