我有一个春季启动应用程序。这些是类:
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
时,网页浏览器上会显示{true}或{false}?
答案 0 :(得分:2)
我不太确定你在做什么。您对控制器的问题是您已经定义了需要布尔参数的方法。鉴于您的场景,这没有意义,因为您不会告诉端点脚本运行的结果;端点告诉你。您的方法返回类型应该是布尔值。
如果它是一个短的运行脚本,通常这将是这样的方法。我用一个简单的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();
}
如果要包装结果,那么您的响应不仅仅是一个真/假字符串。请注意,方法的返回类型已更改为简单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;
}
}
控制器方法
@RequestMapping("/runbatchfile")
public ResultWrapper runbatchFile() {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch();
}