简体   繁体   中英

How to return javascript code to be executed by client in Jersey Rest?

What I am trying to do is that after executing the following REST API the Browser should alert the "Hello World!!" string in the browser.

I thought annotating the function with @Produces("text/javascript") will take care of it. But as I am hitting the resource at the following url

    http://localhost:8080/JAXRS-HelloWorld/rest/script/helloWorld 

JAXRS-HelloWorld is the name of the App and I have specified the url as /rest*

I am getting everything as String. Not as executable Javascript code.

  package com.bablo.rest;

  import javax.ws.rs.GET;
  import javax.ws.rs.Path;
  import javax.ws.rs.Produces;
  import javax.ws.rs.core.Response;
  @Path("script")

 public class JavaScriptTesting {
  @GET
  @Produces("text/javascript")
  @Path("/helloWorld")
  public Response helloWorld(){
        String responseParam = "alert(Hello World!!)";
        return Response.ok(responseParam).build();
    } 
}

How to get the Browser to execute the alert function? Can we achieve this just by doing some trick in the Server Side REST API?

You want the server to execute client-side javascript. This is not going to work.

You need to update your REST client so that the javascript code returned by the server is evaluated:

 var response = callRestApi();
 eval(response);

Or you can return HTML code that embed your script, so that it is evaluated by the browser:

    @GET
    @Path("/test")
    @Produces(value = MediaType.TEXT_HTML)
    public String test() {
        return "<script>alert('test');</script>";
    }
@GET
@Path("/admission")
@Produces(value = MediaType.TEXT_HTML)
public String admission(@QueryParam("id") String id){
    System.out.println("PARAMETRO RECIBIDO : "+id);
    return "<script>alert('Notificacion exitosa');</script>";
}

We use the Command pattern and the window.call() function to execute commands.

The commands need to match the JavaScript methods that you want to execute (that's why the toString() is overridden)

public enum Commands {
  LOAD_BLOCK,

  @Override
  public String toString() {
    String[] parts = name().split("_");
    StringBuilder sb = new StringBuilder();

    // loop through all parts of the name
    for (int i = 0; i < parts.length; i++) {
      String word = parts[i];
      // use a lowercase letter for the first word
      if (i == 0) {
        sb.append(word.toLowerCase());
      // follow camel case pattern (first letter capital)
      } else {
        sb.append(String.valueOf(word.charAt(0)));
        sb.append(word.substring(1, word.length()).toLowerCase());
      }
    }
    return sb.toString();
  }
}

Build and send commands to the Client from the Rest resource

Command load = new Command(Commands.LOAD_BLOCK.toString(), new String[]{"b1"})
return Response.status(200).entity(load).build();

In the JavaScript file prepare a method that calls this Rest resource and run a method such as below that takees a list of commands as input and excutes them with the provided argments.

function triggerEvents(commands){
    for (var index = 0; index < commands.length; index++){
        var command = commands[index];
        console.debug("executing " + command.function);
        await window[command.function].call(null, command.arguments);
    }
}

It will look for a matching function and execute with the given parameters if found

async function loadBlock(blockId) {
  // do some work
}

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