我有一个 Spring Boot 应用程序。这些是类:
RunBatchFile.java
public class RunBatchFile {
private Boolean isSuccessful;
private String content;
public void RunningBatchCommand() {
String filePath = "C:/Users/attsuap1/Desktop/test.bat";
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
if (exitVal == 0)
{
isSuccessful = true;
}
else {
isSuccessful = false;
}
System.out.println(isSuccessful);
} catch (Exception e) {
e.printStackTrace();
}
}
public RunBatchFile(Boolean isSuccessful) {
this.isSuccessful = isSuccessful;
this.content = content;
}
public RunBatchFile(String format) {
// TODO Auto-generated constructor stub
}
public Boolean getisSuccessful() {
return isSuccessful;
}
public String getContent() {
return content;
}
}
BatchFileController
@RestController
public class BatchFileController {
private static final String template = "Sum, %s!";
private static boolean isSuccessful;
@RequestMapping("/runbatchfile")
@ResponseBody
public RunBatchFile runbatchFile(@RequestParam(value = "isSuccessful") Boolean isSuccessful) {
return new RunBatchFile(String.format(template, isSuccessful));
}
}
runBatchFile.java 类执行批处理文件,并将输出显示为 true 或 false,具体取决于批处理文件是否正确执行了其命令。我想在 Web 浏览器上显示该输出,因此我创建了 BatchFileController.java 类。
我收到错误:
Required Boolean parameter 'isSuccessful' is not present
如何编辑代码才能实现此功能?这意味着,当我运行 localhost:8080/runbatchfile
时,网络浏览器上会显示 {true} 或 {false}?
最佳答案
我不太确定你在做什么。您的 Controller 遇到的问题是您已将方法定义为需要 boolean 参数。考虑到您的场景,这是没有意义的,因为您不会告诉端点脚本运行的结果;端点告诉你这一点。您的方法返回类型应该是 boolean 值。
如果脚本运行时间较短,通常可以采用这种方法。我用一个简单的 ping 命令进行了测试,一切顺利。指向无效 IP 失败。
如果脚本花费大量时间,您将需要在提交作业时进行异步,并且可以使用不同的方法回来查看状态。
我会有一个类来运行你的批处理文件:
public class RunBatchFile {
public boolean runBatch() {
String filePath = "C:/Users/attsuap1/Desktop/test.bat";
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
return exitVal == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
然后在你的 Controller 中:
@RequestMapping("/runbatchfile")
public boolean runbatchFile() {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch();
}
如果您想包装结果,以便您的响应不仅仅是一个真/假字符串。请注意,该方法的返回类型已更改为简单的 POJO :
类别
public class RunBatchFile {
public ResultWrapper runBatch() {
String filePath = "C:/Users/attsuap1/Desktop/test.bat";
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
return new ResultWrapper(exitVal == 0);
} catch (Exception e) {
e.printStackTrace();
return new ResultWrapper(false);
}
}
}
包装类
public class ResultWrapper {
private boolean result;
public ResultWrapper(boolean result) {
this.result = result;
}
public boolean getResult() {
return result;
}
}
Controller 方法
@RequestMapping("/runbatchfile")
public ResultWrapper runbatchFile() {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch();
}
关于java - 在网络浏览器中显示输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47584951/