简体   繁体   中英

Javascript inside a java code

I need to write a jax-rs endpoint which returns a javascript function.

I know that we can write java codes inside javascript. But I don't know weather we can write a javascript code inside a java code.

But my supervisor asked me to write it. Any help is appreciated.

Thanks

you can return a string from your code and you can declare html tags as the returning String. I will suggest a sample code.

        @GET
        @Path("/")
        @Produces("text/html")
    public String getStatus(@Context HttpServletRequest request) {
    return "<html><head><script>put your java script code here...</script></head></html>"
}

When you want to use run javascript code inside of java you should take a look at nashorn: http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html http://en.wikipedia.org/wiki/Nashorn_%28JavaScript_engine%29

A very good tutorial on this here: http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

You don't need to execute JavaScript in the server. You only need to return a String representation of the JavaScript function, so the client can execute the returned code dynamically (for instance using eval inside the browser).

On the other hand, if you want to run JavaScript inside the server you can use one of the embedded engines that are available inside the JVM:

Java 1.7: Rhino

http://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/

Java 8: Nashorn

http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html

Take a look at Rhino or Nashorn . The latter was released by Oracle with Java 8.

Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine.

Nashorn is a JavaScript engine developed in the Java programming language by Oracle. It is based on the Da Vinci Machine (JSR 292) and has been released with Java 8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM