1

I was wondering about the possibility to send Java Code to a servlet that the servlet will take and execute it?

For example I would send a chunk of code as String, which will be added and executed. Can anybody think of a way of how I would approach this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
oneiros
  • 3,527
  • 12
  • 44
  • 71
  • 2
    Related: http://stackoverflow.com/questions/2946338/how-do-i-programmatically-compile-and-instantiate-a-java-class/2946402#2946402 – BalusC Feb 21 '12 at 20:51
  • 1
    Could you explain your use case in more detail, specifically why you're trying to execute a `String` at runtime? (That's a pretty serious code smell right there...) – Louis Wasserman Feb 21 '12 at 21:47

2 Answers2

1

This is certainly possible - you could send the compiled bytecode Base64-encoded, then decode it at the servlet and use a classloader to load it.

Or you could send a jarfile similarly encoded, save it to disk and add it to a custom URLClassLoader.

You may have major security issues if the code is untrusted, though.

See What are the security risks I should guard against when running user-supplied Java code?

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146
0

tools.jar from JDK contains classes to compile Java code (used by Ant etc.), you can also use Eclipse compiler, if you want. It is possible, but from security point of view (code injection etc.) it would be disaster ;)

Danubian Sailor
  • 1
  • 38
  • 145
  • 223