groovy 的常用操作


推荐阅读:Springboot中使用Groovy的各种方式

全局变量

方式1:static 定义的全局变量可以在不同的类使用

class Globals {
   
   //定义全局变量
   static Integer NUM;
}
if(Globals.NUM == null){
   
   //初始化
  Globals.NUM = 1;
  println "初始化";
}
//日志输出
println show();

//自定义方法,访问变量
Integer show(){
   
    return Globals.NUM;
}

方式2:使用@Field 定义的全局变量可以在不通的方法间共用

import groovy.transform.Field
//定义全局变量
@Field Integer NUM;
if(NUM == null){
   
   //初始化
    NUM = 1;
    println '初始化';
}
//日志输出
println show();

//自定义方法,访问变量
Integer show(){
   
    return NUM;
}

JSON操作

字符串转json对象:
jsonSlpuer.parse()方法,可以从字符串、文件、byte[]、url、输入流等直接解析为对象。

def jsonSlpuer = new JsonSlurper()
def jsonObj=jsonSlpuer.parseText(str)

对象转json字符串:

package file
 
import groovy.json.JsonOutput
import objectorention.Person
 
def list = [new Person(name: 'John', age: 25),
            new Person(name: 'Major', age: 26)]
println JsonOutput.toJson(list)

发送http

1.get 超简单

def res1 = new URL('http://www.baidu.com').text
// or 
def res2 = 'http://www.baidu.com'.toURL().text
//设置超时时间 ms
def res3 = new URL('http://www.baidu.com').getText(readTimeout: 200000)

2. get 自带请求头

    /**
     * 发送httpGet请求,自带请求头
     * @param url 必填
     * @param headerMap 非必填
     * @return
     */
    static def httpGet(url, headerMap) {
   
        def conn = new URL(url).openConnection()
        conn.setRequestMethod("GET")

        if (headerMap) {
   
            headerMap.each {
    header ->
                conn.setRequestProperty(header.key, header.value)
            }
        }
        return conn.content.text
    }

3. post 传入header和body返回json

    static void main(String[] args) {
   
        def url = "http://demo.com:8088/user/special/list/2/10"
        def data = [:]
        def isJson = true

        def headerMap = [:]
        headerMap.put("Content-Type", "application/json")
        headerMap.put("Cookie", "MS_SESSION_ID=123456")
        headerMap.put("CSRF-TOKEN", "12345")

        def post = httpPostJson(url, data, headerMap, isJson)
        println(post)
    }
	
	//工具方法
    static def httpPostJson(url, body = null, headerMap, isJson = false) {
   
        def conn = new URL(url).openConnection()
        conn.setRequestMethod("POST")

        if(headerMap){
   
            headerMap.each{
   header->
                conn.setRequestProperty(header.key, header.value)
            }
        }
        if (body!=null) {
   
            // 写入body
            conn.doOutput = true
            def writer = new OutputStreamWriter(conn.outputStream)
            writer.write(JsonOutput.toJson(body))
            writer.flush()
            writer.close()
        }

        if(isJson){
   
            def json = new JsonSlurper()
            def result = json.parseText(conn.content.text)
            return result

        }else {
   
            return conn.content.text
        }

    }

SQL操作

sql查询、新增、更新

//数据库连接
def sql = Sql.newInstance('jdbc:mysql://10.0.0.1:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false', 'root', '123456', 'com.mysql.jdbc.Driver')

def saveSumary(String fullName, BigDecimal cost, def sql) {
   
    cost.setScale(2, BigDecimal.ROUND_HALF_UP)
    def percent='10%'
    def row = sql.firstRow('select * from apportion_summary where full_name=?', [fullName])
    if (row == null) {
   
        
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值