How to compile the `.java` file in jsp?

Using java compiler API, I want to compile java fileto jsp. I created an html file and using its element textArea, I sent its text, which is expected to be the code in java entered by the user, in the JSP on the server and after collecting it in a line I made a file with the extension .javaand wrote it with the contents textArea, then I used the compiler API, but it does not compile the file. I want to do something like this

index.html

  <form action="formAction.jsp" method="post">
        Please enter your text:
        <br/>
        <textarea name="textarea1" rows="5"></textarea>
        <br/>
        <input type="SUBMIT" value="Submit"/>
    </form>     

formAction.jsp

 <%

        String convert = request.getParameter("textarea1");
        PrintWriter wr = response.getWriter();
        File f =new File("file121.java");
        if(!f.exists())
        {
            f.createNewFile();
            wr.println("File is created\n");

        }
        FileWriter write = new FileWriter(f);
        BufferedWriter bf = new BufferedWriter(write);
        bf.write(convert);
        bf.close();
        wr.println("File writing done\n");

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int result = compiler.run(null,null,null,"file121.java");
        if(result==0){
            wr.println("Compilation Successful");
        }
        else{
            wr.println("Compilation Failed");
        }




     %>   
-4
source share
2 answers
  • Please do not use scripts, write java code that you can call from your jsp.
  • Java , , , .
  • java-, ? , script ?
  • java, , , !

convert. . , MyClass.

      String convert = "public class NewClass {  public static void main(String[] args) {    System.out.println(\"test\");  }}";
  String filename = "MyClass.java";

  int i = convert.indexOf(" class ");
  if(i == -1) {
    convert = "public class MyClass { " + convert + " } ";
  } else {
    int classNameIndex = convert.indexOf(" ", i+1);
    int classNameIndexEnd = convert.indexOf(" ", classNameIndex+1);        
    filename = convert.substring(classNameIndex+1, classNameIndexEnd) + ".java";
  }

  PrintWriter wr = response.getWriter();
  File f = new File(filename);
  if (!f.exists()) {
    f.createNewFile();
    wr.println("File is created\n");

  }
  FileWriter write = new FileWriter(f);
  BufferedWriter bf = new BufferedWriter(write);
  bf.write(convert);
  bf.close();
  wr.println("File writing done\n");

  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  int result = compiler.run(null, null, null, filename);
  if (result == 0) {
    wr.println("Compilation Successful");
  } else {
    wr.println("Compilation Failed");
  }
+12

, Java- JSP, (EL) , jsp . .

http://www.journaldev.com/2099/jsp-custom-tags-example-tutorial

, Head First Servlet JSP . .

..

+1

All Articles