java实现代码在线编译器-从零开发(二)简单SpringBoot网络接口demo

  • Post author:
  • Post category:java

新建SpringBoot项目

其他语言其他框架也差不多,简单入门写个网络接口还是很快的。
配置文件:

server:
  servlet:
    context-path: /
  port: 8080

工程目录:在这里插入图片描述
TestController.java:

package com.deng.controller;

import com.alibaba.fastjson.JSONObject;
import com.deng.bean.Answer;
import com.deng.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/code",produces = "application/json;charset=UTF-8")
public class TestController {

    TestService service;
    @Autowired
    public void setService(TestService service) {
        this.service = service;
    }
    @RequestMapping(value = "/run")
    public String run(@RequestBody JSONObject json){
        Answer answer=service.run(json.getString("code"));
        if(answer==null)
            return "{\"error\":\"IO错误\"}";
        else
            return JSONObject.toJSONString(answer);
    }
}

TestService.java

package com.deng.service;

import com.deng.bean.Answer;
import com.deng.util.ExecUtil;
import org.springframework.stereotype.Service;
import java.io.FileWriter;
import java.io.IOException;

@Service
public class TestService {
    public Answer run(String code){
        String DIR="d:/javaTest/";
        String javaFile=DIR+"Main.java";
        String javaClass="Main";
        //编译命令
        String compileCmd=String.format("javac -encoding utf8 %s -d %s",javaFile,DIR);
        //运行命令
        String runningCmd=String.format("java -classpath %s %s", DIR, javaClass);
        //将代码写入到定义路径下特定的java源文件中
        FileWriter writer= null;
        try {
            writer = new FileWriter(javaFile);
            writer.write(code);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        //编译源文件为class文件
        Answer answer= ExecUtil.run(compileCmd,false,true);
        System.out.println(answer.getStderr());
        //若编译成功即可开始运行
        if(answer.getError()==0) {
            answer = ExecUtil.run(runningCmd, true, true);
            if(answer.getError()==0)
                answer.setReason(Answer.Success);
            else
                answer.setReason(Answer.RuntimeError);
            System.out.println(answer.getStdout());
        }
        else
            answer.setReason(Answer.Error);
        return answer;
    }
}

确认好本机地址+端口,使用模拟请求软件发送http请求测试,如Postman,Apipost,Apifox(建议使用,有多线程测试功能)
在这里插入图片描述
得到如下返回值(格式为json):

{
    "error": 0,
    "reason": "运行成功",
    "stderr": "",
    "stdout": "hello world\n"
}

下一步

至此已经完成简单的在线Java编译+运行。篇一列出的问题还待解决,下一篇将分析基于Web多线程下的运行,并修改代码来保证正确性。


版权声明:本文为qq_45714068原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。