Java compilation and running within jsp page

hi,
i need of a jsp page that has a textarea in which the java coding are entered and this coding is compiled and executed. The execution result is printed.
Please guide me.

I don't think you can invoke java compiler or run time environment at client side (browser). Even if you use applet, i think you will not be able to do it at client side. Moreover, though java virtual machine will be available in your target user's browser, but you should not expect a java compiler in users machine.
I have seen exam sites where they have added java code compilation and execution ability. To achieve this you can do:
1. In your JSP page use text area where user can edit java code.
2. Provide two buttons - 'Compile' and 'Run'.
3. On click of 'Compile' send the code to server side. In server machine create a file in a temporary location in disk and save the code content received from client.
4. Invoke 'javac' command (as a separate process) to compile the java class created in step 3. This process will give you error/output back which you can send back to user.
5. In case of 'Run' you must first invoke above mentioned 'Compile' service and then another service ('Run') to actually run you java class. You can build 'Run' service in similar way.
Here you challenge would be managing multiple client requests (to compile and run java class) at the same time.
Code to compile and run java classes:
import java.io.*;
* A class to compile and run java classes.
* @author Mrityunjoy Saha
public class JavaProcessor{
     public static void main(String[] args){
          // Option 1 to compile and option 2 to run.
          int option=1;
          if(args.length > 0){
               option=Integer.parseInt(args[0]);
          JavaProcessor p=new JavaProcessor();
          if(option==1){
               p.compile();
          } else {
               p.run();
     public void run(){
          String file="FoodTest";
          String directory="C:/Users/mrityunjoy_saha/Documents/Test";     
          executeCommand("java", directory, file);
     public void compile(){
          String file="FoodTest.java";
          String directory="C:/Users/mrityunjoy_saha/Documents/Test";     
          executeCommand("javac", directory, file);
     public void executeCommand(String command, String directory, String file){
          try{
               String[] envp=null;
               // Make sure that you have done Java setup in your machine.
               // To test this try invoking javac command in command prompt.
               Process p=Runtime.getRuntime().exec(command+" "+file,envp,new File(directory));
               BufferedReader errorStream=new BufferedReader(new InputStreamReader(p.getErrorStream()));
               String readData="";
               while((readData=errorStream.readLine())!=null){
                    System.out.println(readData);
               BufferedReader outStream=new BufferedReader(new InputStreamReader(p.getInputStream()));
               readData="";
               while((readData=outStream.readLine())!=null){
                    System.out.println(readData);
          catch(IOException ioe){
               ioe.printStackTrace();
}Thanks,
Mrityunjoy

Similar Messages

  • Java compile and run time questions

    Hello, I have two generic question about java compile and run:
    1. When I used javac to compile my project, it complained some classes can't be found. I added the jar file which contains these needed classes to the jre/lib/ext/ directory. The compiler no longer complains. But I'm confused. I thought the jar files in jre/lib/ext/ only used for java run time, not the compile time. Can someone help me to explain this?
    2. If I need certain user defined jar file in the classpath to compile my application, does that imply that I have to have that jar file if I want to run my project?
    Thanks in advance.

    1. lib/ext is used for generally finding classes, it doesn't matter whether you are compiling or running.
    2. Yes, you will.

  • Accessing java class and methods within JSP

    Hi All,
    I am writing a JSP page, and need to instantiate an object of a certain class within my package, in my JSP page.
    How do I do that? Do i use the <%import = "Whatever.class" %>
    Any help would be greatly appreciated.
    Kal.

    Hi.. Thanks for ur reply.
    I am actually having a problem with the import statement. So the part where you have mypackage.Myclass, it is not working for me.
    I am using Sun Forte.. and the directory is myprojects/test/Classes/MyClass.java
    so how would the import statement look like?
    Thanks
    Kal.
    Using directive for import statements:
    <%@ page
    import="java.util.*,java.sql.*,mypackage.MyClass" %>
    Then use scriptlet:
    <%! MyClass c= new MyClass(); %>
    <%! private void method() {...} %>
    <%= c.getxxx() %>
    ...and so on

  • How can I compile and run other java classes from within an application?

    Hello there everyone! I really hope that someone can help me. I am writing a program that must be able to compile and run other java classes that are in different files, much like development environments like Kawa or Forte allow you to do.
    There has to be a way of doing this ( I hope!! ), but i can't seem to find it!!
    I have tried using this command to compile:
    Runtime.getRuntime().exec ("c:\\programs\\javac className.java");
    ...and this one to run:
    Runtime.getRuntime().exec ("c:\\programs\\java className");
    ...but neither works!!! I can compile and run classes that are in the same file as my application, but I can't get it to work at all for files in different directories or files.
    PLEASE, PLEASE, PLEASE help me - i've run out of ideas, and i need this to be working in 3 days!!!
    Thank you very much for any help anyone can give me, I really appreciate it!! Thanks again!!
    Adrian ( ...in distress!! )

    public class JavaCompiler{
       public static void main(String[] args)throws Exception{ //sorry bout the laziness
          if(args == null || args.length != 1){
             System.out.println("Usage: java JavaCompiler MyClass.java");
             System.exit(0);
          String className = args[0];
          Runtime rt = Runtime.getRuntime();
          Process p = rt.exec("javac " + className); //consider setting cpath for this
          p.waitFor();
          //now try to run after it is done.
          p = rt.exec("java " + className.substring(0, (className.length() - ".java".length()));
          p.waitFor();
          //do some other stuff
    }This should get you going. You may consider looking into the System.getProperty() method in order to determine the type of OS it is running on in order to findo out what command to run. I know that the sun tool listed above is nice, but by my understanding the sun tools provided are not guaranteed to stay the same. I'm no expert on this matter, but that is one of the reasons there is no API documentation for those tools. Also, I don't believe those tools come packaged with the JRE. (Of course if you are making an IDE it will be expected that the user has an sdk installed. Good luck with figuring this thing out.

  • I'm trying to run a .jsp page and all I get is the following error. Thoughts?

    Running Coldfusion 8 / JRun 4 updater 7 / Coldfusion 8 hotfix
    2.
    I'm trying to run a .jsp page and all I get is the following
    error. Thoughts?
    Could not invoke Java compiler, please make sure jikesw is in
    I:\JRun4/bin or put a JDK bin directory in your path.
    jrunx.compiler.JavaCompiler$NoCompilerFoundException: Could
    not invoke Java compiler, please make sure jikesw is in
    I:\JRun4/bin or put a JDK bin directory in your path.
    at
    jrunx.compiler.JavaCompiler.outProcessCompile(JavaCompiler.java:474)
    at
    jrunx.compiler.JavaCompiler.compile(JavaCompiler.java:132)
    at
    jrunx.compiler.JavaCompiler.compile(JavaCompiler.java:100)
    at jrun.jsp.Translator.compilePage(Translator.java:176)
    at jrun.jsp.Translator.translate(Translator.java:254)
    at jrun.jsp.Translator.translate(Translator.java:101)
    at jrun.jsp.JSPEngine.translateJSP(JSPEngine.java:707)
    at jrun.jsp.JSPServlet.translate(JSPServlet.java:125)
    at jrun.jsp.JSPServlet.service(JSPServlet.java:113)
    at
    jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106)
    at
    jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42)
    at
    jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286)
    at
    jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543)
    at
    jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203)
    at
    jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428)
    at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)

    You're right, that ws another fix I tried. There is no fix fo
    rthe issue described, but it still seems like an old issue. My
    class paths are short. Here is my jvm.config (pretty standard):
    # VM configuration
    # Where to find JVM, if {java.home}/jre exists then that JVM
    is used
    # if not then it must be the path to the JRE itself
    java.home=I:/JRun4/jre
    # If no java.home is specified a VM is located by looking in
    these places in this
    # order:
    # 1) bin directory for java.dll (windows) or
    lib/<ARCH>/libjava.so (unix)
    # 2) ../jre
    # 3) registry (windows only)
    # 4) JAVA_HOME env var plus jre (ie $JAVA_HOME/jre)
    # Arguments to VM
    java.args=-server -Xmx1000m -Dsun.io.useCanonCaches=false
    -XX:MaxPermSize=256m -XX:+UseParallelGC
    -Dcoldfusion.rootDir={application.home}/
    # commas will be converted to platform specific separator and
    the result will be passed
    # as -Djava.ext.dirs= to the VM
    java.ext.dirs={jre.home}/lib/ext
    # where to find shared libraries
    java.library.path={application.home}/lib,{application.home}/servers/cfusion/cfusion-ear/cf usion-war/WEB-INF/cfusion/lib,{application.home}/servers/cfusion/cfusion-ear/cfusion-war/W EB-INF/cfusion/jintegra/bin,{application.home}/servers/cfusion/cfusion-ear/cfusion-war/WEB -INF/cfusion/jintegra/bin/international
    system.path.first=false
    # set the current working directory - useful for Windows to
    control
    # the default search path used when loading DLLs since it
    comes
    # before system directory, windows directory and PATH
    java.user.dir={application.home}/../lib
    # JVM classpath
    java.class.path={application.home}/servers/lib,{application.home}/lib

  • Compiling and running jsp-code on the fly.

    I am intending to use jsp as a report engine. The 'templates' should be jsp-code stored in the db, loaded and executed as if they where inside a plain jsp-file in the application. I cannot write new files on the file system since this is prohibited on the production env - so I would like to compile and execute the jsp-code directly in memory.
    Was hoping this could be done with the jee standard stack.
    Does anybode know how to to this, if possible?

    If you just want to run java applications, you just need the JRE: J2SE 5.0 JRE
    If you want to compile java source code, you need the JDK: J2SE 5.0 JDK
    It includes also the JRE. Recommended is also the J2SE 5.0 Documentation that contains the javadoc API that describes all the Java classes.
    To start develeoping I recommend the Java Tutorial: http://java.sun.com/docs/books/tutorial/

  • How to compile and run a java program?

    I am getting this error message, what to do?
    Exception in thread "main" java.lang.NoClassDefFoundError:
    Thanks for you help.
    Ajay

    Hello,
    I believe that this error is caused because when you
    compile and run a java program, you have to use the
    same name that is next to public class. For example,
    the program name is next to the word public class.
    For example, if a program began like this:
    public class Concat
    then the name of the program in this case is Concat
    and when you compile it you type: javac Concat.java
    when you run it type: java Concat
    depending on the name of your program.and depending on whether the class is in a package. And depending on what directory you are currently in.
    Also depending on if you set your class path you might
    have to type the above like this: jdk1.2.1\bin\javac
    Concat.java to compile, and to run you would have to
    type jdk1.2.1\bin\java Concat where you would replace
    Concat with the name of your program and replace
    jdk1.2.1 with the name of your version of java, that
    is again if you do not have your classpath set. Hope
    this helps.Your examples have nothing to do with whether the CLASSPATH is set--only with whether the PATH is set. And, it may not be jdkXXX\bin. The path to the JDK (in this case, to javac and java executables) could be anything. Classpath should be set on the command line. The OP probably did NOT set a classpath on the command line (preferred), or in the environment variables.
    Also, make sure you did not forget to put:
    public static void main(String[ ] args)
    on the line underneath the line where it says "public
    class Concat" where Concat is the name of your
    program. Again, I hope this helps.Irrelevant (with the info we have from the OP so far). The error says that the JVM can't even find the class--not that the class doesn't have a main. The "main" referred to in the error message is within the JVM itself.
    OP: Did you fix your problem? If not, what directory are your files in? Are they in a package? What command are you typing to get that error? That is, please tell us your entire command line.

  • How do I compile and run Java programs on a Mac?

    To clarify my earlier post, I know that you can write java in any text editor but with the PC you compile and run everything through the MS DOS prompt, what is the Mac equivalent?

    See this question :-)
    http://forum.java.sun.com/thread.jsp?forum=54&thread=289574

  • How to compile other java files and run them from my own programs?

    I'm developing a unit testing tool for AspectJ, which can originally generate the stubs for aspect unit to be tested. All these stubs are java files. After generation of stubs, how can I program the code to compile this unit together with these stubs, i.e. how can I put the functionality of compilation and run, e.g. command "javac *.java" and "java *", into my own code.
    Hope you can understand what I mean.
    Thank you in advance.

    When I use Runtime.getRuntime().exec(command) for executing the AspectJ compile command "ajc", "IOException createProcess error=2" always occurs, while it is ok for Java comiple command "javac".
    Why this happens when I use Runtime.getRuntime().exec("ajc Hello.java Test.aj")? Is it the reason that Runtime.exec(String) may not support any command in DOS?
    (ajc is the compile command for the java file and aj file.)
    Thank you in advance.

  • How to Set up the  variables and others to compile and Run Java Programs

    Hello,
    I have just downloaded the jdk1.6.0_07 and jre1.6.0_07 and installed it in C:\Program files\Java in my Windows XP ,So please tell me how to sett up the enviroment variables etc to compile and run Java Programs from Command Prompt.
    thanks

    To set the PATH permanently, add the full path of the jdk1.6.0_<version>\bin directory to the PATH variable. Typically this full path looks something like C:\Program Files\Java\jdk1.6.0_<version>\bin. Set the PATH as follows on Microsoft Windows:
    1. Click Start > Control Panel > System on Windows XP or Start > Settings > Control Panel > System on Windows 2000.
    2. Click Advanced > Environment Variables.
    3. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:
    C:\Program Files\Java\jdk1.6.0_<version>\bin

  • How to compile and run java files on a mac using command line?

    can someone tell me or link me to some article on how to compile and run java files from command line on a mac? I have mac OS X leopard

    What do you mean by "where to put them" ? What do you want to put anywhere ?
    Have you read Peter's comment in brackets ? Perhaps you have a classpath problem ?
    Edited by: Michael_Knight on Aug 31, 2008 4:23 AM

  • How to compile and run package programs in Java

    Hi,
    I want to know how to compile and run the package programs in Java using -d. instead of creating the package folder manually.
    eg:
    package Test;
    class test1
    public void disp()
    //Any code;
    I want to compile this without creating the folder ' Test ' manually. that is if we use -d with javac the Test folder will be created automatically. I need the format of -d
    could anyone please help me.
    Thanks in Advance ,
    Ambika

    My program Test.java in F:\Tomcat5\webapps\Ambika\WEB-INF\Classes. I compiled in the format below. I got like this. What should I do for this? But yesterday I compiled like this only, It compiled and the folder com\cert\Test.class is created. Today again I compiled the pgm after deleting the already created folder 'com\cert', I got the error like this.
    I've given my pgm and the thing I've got when I compiled it.
    Test.java
    package com.cert;
    public class Test
         public void display()
              System.out.println("Hai");
    F:\Tomcat5\webapps\Ambika\WEB-INF\Classes>javac -d F:\Tomcat5\webapps\Ambika\WEB-INF\Classes\Test.java
    javac: no source files
    Usage: javac <options> <source files>
    where possible options include:
    -g Generate all debugging info
    -g:none Generate no debugging info
    -g:{lines,vars,source} Generate only some debugging info
    -nowarn Generate no warnings
    -verbose Output messages about what the compiler is doing
    -deprecation Output source locations where deprecated APIs are u
    sed
    -classpath <path> Specify where to find user class files
    -cp <path> Specify where to find user class files
    -sourcepath <path> Specify where to find input source files
    -bootclasspath <path> Override location of bootstrap class files
    -extdirs <dirs> Override location of installed extensions
    -endorseddirs <dirs> Override location of endorsed standards path
    -d <directory> Specify where to place generated class files
    -encoding <encoding> Specify character encoding used by source files
    -source <release> Provide source compatibility with specified release
    -target <release> Generate class files for specific VM version
    -version Version information
    -help Print a synopsis of standard options
    -X Print a synopsis of nonstandard options
    -J<flag> Pass <flag> directly to the runtime system
    F:\Tomcat5\webapps\Ambika\WEB-INF\Classes>
    Plz help me.
    thanks in advance
    Ambika

  • Compile and run java programs in different directroy

    Hi,
    I often encounter many problems when I run java programs in the different directories. Like
    javac -d dir_name a.java
    java -cp dir_name a
    Something wired often happens, such as, there is not a.java file in some directory, but javac -d dir_name a.java can still work or "java -cp dir_name a" often doesn't work. Moreover, file_name.jar is also a tough problem and solving compiling problems is often time-consuming.
    So I hope to read something about how to compile and run java programs in different directory properly.
    Could you pleae give me a detailed description for that or recommend a book or website?
    Thanks a lot.

    Can you post a small amount of code that does not work, including the directory structure, and the error messages? Some one here can likely explain the problem.

  • How to compile and run a .java file from another java program

    hello,
    can any one tell me how to compile and run a *.java* file from another java program which is not in same directory?

    Well a smarter way of implementing this is by using a solution provided by Java Itself.
    If you are using J2SE 6.0+ there is an in built solution provided along with JDK itself and inorder to go ahead with solution the below are set of API which you;d be using it for compiling Java Programs (Files)
    http://java.sun.com/javase/6/docs/api/javax/tools/package-summary.html
    How do i do that ??
    Check out the below articles which would help you of how to do that
    http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
    http://www.javabeat.net/javabeat/java6/articles/java_6_0_compiler_api_1.php
    http://books.google.com/books?id=WVbpv8SQpkEC&pg=PA155&lpg=PA155&dq=%22javax+tools%22+compiling+java+file&source=web&ots=XOt0siYe-f&sig=HH27ovuwvJgklIf8omTykUmy-eM
    Now once we are done with compilation.In order to run a Specific class all you ought to do is create an object and its specific methods of a specified class included in the CLASSPATH which you can manage it easily by usage little bit reflections.
    Hope that might help :)
    REGARDS,
    RaHuL

  • How to compile and run java program at command console

    hi there
    can anyone tell me how to compile and run a java program at command console? I have installed JRE 1.3.1, and also have installed JBuilder 5 if it helps.

    try this
    System.out.println("Enter your Name : ");
    BufferedReader console = new BufferedReader( new InputStreamReader( System.in ) );
    String s = console.readLine();
    System.out.println("Hello : "+ s+" !" );

Maybe you are looking for

  • How to find out the email you used as a backup

    I cannot remember the email address that I associated with my account as an alternative address. Is there any way of finding out this address? Please help as I am trying to retrieve a new password!

  • I'm so disappointed with this software, very frustrated and I hate it. I want to return it.

    I'm using Adobe Premiere Elements 11 and had the worst 3 hours trying to edit a 1:30 minute clip. I bought it on Amazon and they wont let me return it. I've been using Photoshop for years and years and find PS to be very intuitive, what you see is wh

  • Problem in installing Coldfusion 8 in Redhat Enterprise

    I'm trying to install coldfusion 8 (64bit) into my Linux Redhat Enterprise version 5. I can setup everything successfully if using CF default web server. But when i trying to install CF8 with apache webserver, CF unable to point to the conf file whic

  • Java.rmi.servererror

    I am trying to acce ss a method on the client from the server. The method on the client is not accessible instead a exception is thrwon on the client java.rmi.ServerError Error occurred in Server Thread , nested exception is java.lang.AbstractMethodE

  • How to uninstall Command Line Developer Tools

    Hello, After upgrade to OSX Mavericks by mistake I downloaded Command Line Developer Tools. I'm not a coder, just a graphic designer and I'm not gonna need it. It's about 300 MB size and I don't want it. The worst part is that its the second time App