Java中调Groovy

前提: springMVC项目已搭建好。

模拟:前台调后台Controller--->service---->groovy文件--->返回或者操作业务

[color=blue]创建处理Groovy的公用类[/color]
里面的存放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;
}

}



[color=blue]项目的controller层[/color]

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盘根目录
[color=blue]Test.Groovy[/color]

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()


[color=blue]hello.groovy[/color]

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博客中上传
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值