我有一个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类。
我得到错误:
必需的布尔参数'issuccessful'不存在
如何编辑我的代码以使这项工作?当我运行localhost:8080/runbatchfile
时,在Web浏览器上显示{true}或{false}的意思是?
我不太确定您在做什么。您对控制器的问题是您已经定义了需要布尔参数的方法。考虑到您的情况,这是没有意义的,因为您不会告诉端点脚本运行的结果;终点告诉您。您的方法返回类型应该为布尔值。
通常,如果它是一个简短的运行脚本,这将是解决这个问题的方法。我用一个简单的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;
}
}
}
然后在您的控制器中:
@RequestMapping("/runbatchfile")
public boolean runbatchFile() {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch();
}
如果要包装结果,以便您的响应不仅仅是一个true/false字符串。请注意,该方法的返回类型已更改为简单的POJO:
class
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;
}
}
控制器方法
@RequestMapping("/runbatchfile")
public ResultWrapper runbatchFile() {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch();
}