How to compile java code from jsp page durining runtime

plz help me how to take java code in a text box from the user and compile and show the result online of the code inputted by the user
[140 byte] By [Ankoor_Mehtaa] at [2007-10-2 22:06:24]
# 1

See http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javac.html#proginterface

Assuming that the user input consists of only simple statements (without method and/or class declarations and such), the following method generated a corresponding source file, compiles and executes it. Currently, the output is not collected, but I'm pretty sure you'll be able to adopt the code to your individual needs.

public void generateAndExecute(String in) throws Exception {

// create the source file

File f = new File(new File(System.getProperty("user.dir")), "Base.java");

f.deleteOnExit();

BufferedWriter w = new BufferedWriter(new FileWriter(f));

w.write("public class Base {");

w.newLine();

w.write("public static void main(String[] args) {");

w.newLine();

w.write(in);

w.newLine();

w.write("}}");

w.newLine();

w.close();

// search for directory in class path

String cp = System.getProperty("java.class.path");

StringTokenizer st = new StringTokenizer(cp, System.getProperty("path.separator"));

String targetDir = null;

while (st.hasMoreTokens() && targetDir == null) {

File tmp = new File(st.nextToken());

if (tmp.isDirectory())

targetDir = tmp.getAbsolutePath();

}

if (targetDir == null)

throw new FileNotFoundException("No directory entries in class path!");

// compile the source file

int compileResult = Main.compile(new String[] {

"-sourcepath", f.getParentFile().getAbsolutePath(),

"-d", targetDir,

f.getName()

});

// execute the source file

switch (compileResult) {

case 0:

Class<?> clazz = Class.forName("Base");

Class<? extends Object> stringArrayClass = Array.newInstance(String.class, 0).getClass();

Method mainMethod = clazz.getMethod("main", stringArrayClass);

mainMethod.invoke((Object) null, (Object) null);

default:

throw new Exception("Compiler exited with return value other than 0!");

}

}

falke2203a at 2007-7-14 1:23:05 > top of Java-index,Java Essentials,Java Programming...
# 2
Which Main class is used in the following line:int compileResult = Main.compile(new String[] { The compile method is undefined in this class.
staaouata at 2007-7-14 1:23:05 > top of Java-index,Java Essentials,Java Programming...
# 3
com.sun.tools.javac.Main (The poster above gave you the link - its all in there...)
aconst_nulla at 2007-7-14 1:23:05 > top of Java-index,Java Essentials,Java Programming...
# 4
Running this code to compile my java source gives following error:package "nl.core.util" (my package) does not existAny idea why this package can not be found?
staaouata at 2007-7-14 1:23:05 > top of Java-index,Java Essentials,Java Programming...