java - 动态参数重构
问题描述
我想使用 spring mvc 控制器来获取用户输入命令和参数,然后调用 sendCommand 方法。
调用url如:
http://127.0.0.1:8090/offheap/cmd?command=set a 1 b 2 c 3
控制器将接受以下命令作为字符串。
设置 a 1 b 2 c 3
然后它会调用 sendCommand 方法来设置 key a, value 1; 键 b,值 2;键 c,值 3 到本地缓存中。
控制器代码如下:
@ResponseBody
@RequestMapping(value = "/offheap/cmd")
public String userInput(@RequestParam String command) {
String[] commandArray = command.split(" ");
String cmd = StringUtils.upperCase(commandArray[0]);
Object result;
if (commandArray.length > 1) {
//TODO, how to construct the args??
byte[][] args = null;
result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd), args);
} else {
result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd));
}
return JSON.toJSONString(result);
}
SendCommand 方法代码如下:
public Object sendCommand(OffheapCacheCommand command, byte[]... args) {
//logic here, will ignore.
}
我知道 byte[]...args,应该构造一个 byte[][] 数组,其中包含要传递给 sendCommand 方法的数据。
但问题是 byte[][] 数组很难构造。
有人有好主意来构造这个 byte[][] 数组吗?
解决方案
根据下面的代码解决了它。
public String sendCommand(@RequestParam String command, @RequestParam String args) {
String cmd = StringUtils.upperCase(command);
String[] argsArray = args.split(" ");
Object result;
if (argsArray.length > 0) {
byte[][] byteArray = new byte[argsArray.length][];
for (int i = 0; i < argsArray.length; i++) {
byte[] element = SerializationUtils.serialize(argsArray[i]);
byteArray[i] = element;
}
result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd), byteArray);
} else {
result = ohcCacheStrategy.sendCommand(OffheapCacheCommand.valueOf(cmd));
}
return JSON.toJSONString(result);
}
推荐阅读
- asp.net-mvc - 在 MVC 中将数据导入 ViewModel
- php - Laravel 中的 MVC 模式应该是怎样的?
- javascript - 如何创建仅导出 JSON 的节点配置模块
- javascript - 将日期字符串正确解析为时间戳?
- ios - 如何在 React Native 0.60+ 中添加原生模块?
- youtube-api - YouTube Data API v3 搜索缺失的视频
- amazon-web-services - 如何在公共网络中制作 docker swarm 网络?
- django - 从帖子链接重定向到文件的问题
- jquery - 尝试从使用“追加”切换到具有 [0] 和变量的“追加”
- c# - 添加新的 XEelement 并更新 XML.Descendent