You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JMeter BeanShell中字符串分割变量报错:问题原因及修复方法

问题:JMeter BeanShell脚本分割变量报错

场景

尝试用BeanShell脚本通过@分隔符拆分JMeter变量gotDataCloseOrder,脚本如下:

String[] words = ${gotDataCloseOrder}.split("@");
String ClosedOrderAccessToken = words[1];
String CloseOrderOrderId = words[0];
log.info("ClosedOrderAccessToken",ClosedOrderAccessToken);
log.info("CloseOrderOrderId",CloseOrderOrderId); 

变量gotDataCloseOrder的示例值:

6362cb2ab4f4ed3897cfb5cc@eyJhbGciOiJIUzUxMiJ9.eyJ0eXBlIjoiZ3Vlc 

执行错误

2022-11-02 23:25:40,434 WARN o.a.j.m.BeanShellPreProcessor: Problem in BeanShell script. 
org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval  In file: inline evaluation of: 
``String[] words = 6362cb2ab4f4ed3897cfb5cc@eyJhbGciOiJIUzUxMiJ9.eyJ0eXBlIjoiZ3Vlc . . . '' 
Encountered "cb2ab4f4ed3897cfb5cc" at line 1, column 22.

问题原因

直接使用${gotDataCloseOrder}引用变量时,JMeter会把变量值直接替换到脚本中,导致脚本变成:

String[] words = 6362cb2ab4f4ed3897cfb5cc@eyJhbGciOiJIUzUxMiJ9.eyJ0eXBlIjoiZ3Vlc.split("@");

这不符合Java语法——没有引号包裹的内容会被当成标识符,@符号也会被解析为非法语法,最终触发编译报错。

修复方案

有两种可靠的修改方式:

方式1:用引号包裹变量引用

给${gotDataCloseOrder}加上双引号,让它成为合法的字符串字面量:

String[] words = "${gotDataCloseOrder}".split("@");
String ClosedOrderAccessToken = words[1];
String CloseOrderOrderId = words[0];
log.info("ClosedOrderAccessToken",ClosedOrderAccessToken);
log.info("CloseOrderOrderId",CloseOrderOrderId); 

方式2:使用JMeter API获取变量(更推荐)

通过BeanShell内置的vars对象获取变量值,避免直接替换带来的语法问题,同时支持变量为空等边界场景:

String rawData = vars.get("gotDataCloseOrder");
// 先判断变量是否为空,避免空指针异常
if (rawData != null && !rawData.isEmpty()) {
    String[] words = rawData.split("@");
    String ClosedOrderAccessToken = words[1];
    String CloseOrderOrderId = words[0];
    log.info("ClosedOrderAccessToken", ClosedOrderAccessToken);
    log.info("CloseOrderOrderId", CloseOrderOrderId);
    // 可选:将拆分后的值存回JMeter变量,供其他组件使用
    vars.put("ClosedOrderAccessToken", ClosedOrderAccessToken);
    vars.put("CloseOrderOrderId", CloseOrderOrderId);
}

额外提示

如果使用JMeter 3.1及以上版本,建议优先使用JSR223 PreProcessor配合Groovy脚本,性能比BeanShell更优,语法也更简洁:

def rawData = vars.get("gotDataCloseOrder")
if (rawData) {
    def words = rawData.split("@")
    vars.put("CloseOrderOrderId", words[0])
    vars.put("ClosedOrderAccessToken", words[1])
    log.info("CloseOrderOrderId: ${words[0]}, ClosedOrderAccessToken: ${words[1]}")
}

内容的提问来源于stack exchange,提问作者Ali Kianinejad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:25:38