`
fatedgar
  • 浏览: 137142 次
  • 性别: Icon_minigender_1
  • 来自: 安徽
社区版块
存档分类
最新评论
阅读更多
前提: 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博客中上传
分享到:
评论

相关推荐

    jni学习demo

    JNI(Java Native ...在"CmakeJniDemo"项目中,我们了解了如何设置CMake构建环境,编写C++ JNI函数,以及在Java中调用这些函数。同时,也学习了如何在C++中反向调用Java方法,进一步丰富了Android应用的开发能力。

    android接入穿山甲广告.zip

    这通常涉及到创建Java对象的JNI函数,以及在C++中调用这些函数的接口。例如: ```cpp extern "C" { JNIEXPORT void JNICALL Java_com_your_package_Name BannerCreate(JNIEnv *env, jobject /* this */, jstring ...

    封装GreenDao

    它在后台线程执行`doInBackground`方法,加载所有用户,然后在`onPostExecute`中调用回调,将结果传递回UI线程。 **四、使用封装的GreenDao** 在Activity或Fragment中,我们可以通过调用`fetchUsers`方法获取数据...

    Jenkinsfile调用jdk命令和maven或grandle编译命令工具配置

    为了实现这一点,我们需要在 Jenkinsfile 中调用这些命令。但是,我们面临的一个问题是:如何在 Jenkins 容器中调用这些命令,而不需要在容器中安装 JDK 环境或 Maven/Gradle 命令?今天,我们将探讨如何配置 ...

    android gif图片播放、暂停

    ```groovy dependencies { implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.8' } ``` 然后,同步Gradle项目,使新引入的库生效。 接下来,创建一个`ImageView`或者自定义的视图来显示GIF图像。在...

    安卓高德地图开发(1)——地图显示

    最后,别忘了在Activity的生命周期方法中管理`MapView`的状态,例如在`onResume`、`onPause`、`onDestroy`中调用相应的`onResume()`、`onPause()`、`onDestroy()`方法。 以上就是“安卓高德地图开发(1)——地图...

    typekit,.zip

    通过在应用程序的入口类(如Application)中调用相应的API,可以快速为整个应用或特定的文本样式指定新的字体。例如,开发者可以这样使用Typekit: ```java Typekit.typeface("path_to_font.ttf", R.style.AppTheme...

    Android SDK Manager build-tools升级文件21.1.2版本build-tools_r21.1.2-windows.rar

    这些工具包括但不限于AAPT(Android Asset Packaging Tool)用于处理资源文件,dx用于将Java字节码转换为Dalvik字节码,以及ProGuard和R8(代码瘦身工具)等。`build-tools`的版本更新通常会引入性能优化、新功能...

    GaodeMapTest1:Android开发-在Android项目里调用基于高德地图API实现定位

    本项目"GaodeMapTest1"专注于讲解如何在Android应用中调用高德地图API来实现定位功能。下面我们将深入探讨这个主题。 首先,集成高德地图API需要在项目的build.gradle文件中添加相应的依赖库。在dependencies块中,...

Global site tag (gtag.js) - Google Analytics