请优化以下java代码 @PostMapping("/uploadOriginPackInfo") @ResponseBody public Message uploadGeneratePackInfo(@RequestBody Map<String, Object> dataMap) { String userName = (String) dataMap.get("user"); userName = Sutil.responseFilter(userName); String fileName = (String) dataMap.get("fileName"); fileName = Sutil.responseFilter(fileName); String productType = (String) dataMap.get("productType"); productType = Sutil.responseFilter(productType); List<String> machineTypes = (List<String>) dataMap.get("machineType"); machineTypes = Sutil.responseFilter(machineTypes); String version = (String) dataMap.get("version"); version = Sutil.responseFilter(version); String fileType = (String) dataMap.get("fileType"); fileType = Sutil.responseFilter(fileType); if ((null == userName) || (null == fileName) || (userName.length() <= 0) || (fileName.length() <= 0)) { return new Message().error(500, "invalid params"); } VoUpgradePackInfo voPackInfo = upgradePackService.updateGeneratePackInfo(userName, fileName, productType, machineTypes, version, fileType); List<VoUpgradePackInfo> voPackInfoList = new ArrayList<>(); voPackInfoList.add(voPackInfo); Message message = new Message(); message.addData("count", voPackInfoList.size()); message.addData("list", voPackInfoList); return message.ok(); }
时间: 2024-04-14 19:31:23 浏览: 103
@Response和@Request
以下是优化后的Java代码:
@PostMapping("/uploadOriginPackInfo")
@ResponseBody
public Message uploadGeneratePackInfo(@RequestBody Map<String, Object> dataMap) {
String userName = Sutil.responseFilter((String) dataMap.get("user"));
String fileName = Sutil.responseFilter((String) dataMap.get("fileName"));
String productType = Sutil.responseFilter((String) dataMap.get("productType"));
List<String> machineTypes = Sutil.responseFilter((List<String>) dataMap.get("machineType"));
String version = Sutil.responseFilter((String) dataMap.get("version"));
String fileType = Sutil.responseFilter((String) dataMap.get("fileType"));
if (userName == null || fileName == null || userName.isEmpty() || fileName.isEmpty()) {
return new Message().error(500, "invalid params");
}
VoUpgradePackInfo voPackInfo = upgradePackService.updateGeneratePackInfo(userName, fileName, productType, machineTypes, version, fileType);
List<VoUpgradePackInfo> voPackInfoList = Collections.singletonList(voPackInfo);
Message message = new Message();
message.addData("count", voPackInfoList.size());
message.addData("list", voPackInfoList);
return message.ok();
}
优化说明:
1. 使用链式编程方式进行变量赋值和过滤,减少代码行数。
2. 使用 isEmpty() 方法来判断字符串是否为空,更加简洁。
3. 将 List 初始化为只包含一个元素的列表,使用 Collections.singletonList() 方法代替手动创建 ArrayList 并添加元素。
4. 删除不必要的类型转换和赋值语句,直接在方法调用中进行转换和过滤操作。
5. 优化代码的可读性和格式,使其更易于阅读和理解。
请注意,这只是一种优化方式,具体的优化策略可能因项目需求和个人偏好而异。
阅读全文