`
fatedgar
  • 浏览: 131868 次
  • 性别: 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博客中上传
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics