有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript通过Java方法重定向到另一个servlet路径

我在doGet中有一个方法,如果日期不等于今天,它将启动一个线程。调度程序将找到execute()方法。在这个方法()中,我尝试使用重定向

方法1: 我使用ScriptEngine通过Java调用我的js方法,但它总是给我以下错误:

Js方法:

function httpGet(theUrl){
window.open(theUrl)
}

Java方法:

ScriptEngine engine = manager.getEngineByName("js");
              // read script file

              engine.eval(Files.newBufferedReader(Paths.get(url), StandardCharsets.UTF_8));
              Invocable inv = (Invocable) engine;
              // call function from script file
              inv.invokeFunction("httpGet", "http://localhost:8080/myProject/StartScript?duration="+minutes);

错误:

javax.script.ScriptException: ReferenceError: "window" is not defined in <eval> at line number 3
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:190)
at watering.WateringScheduler.execute(WateringScheduler.java:99)
at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)Caused by: <eval>:3 ReferenceError: "window" is not defined

方法2:

我尝试使用HttpUrlConnection,但问题是它从未将我重定向到页面,即使它已连接

 URL url;
              log.info("hi "+ minutes);
              url = new URL("http://localhost:8080/myProject/StartScript?duration="+minutes);
              HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
              urlConnection.setDoOutput(true);
              urlConnection.setRequestMethod("GET");
              urlConnection.connect();
              BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
              int responseCode = urlConnection.getResponseCode();
              System.out.println(responseCode);
              if(responseCode==200) {
                  urlConnection = (HttpURLConnection) url.openConnection();
                  System.out.println("Redirect to URL : " + url);
              }
              BufferedReader in = new BufferedReader(
                      new InputStreamReader(urlConnection.getInputStream()));
                String inputLine;
                StringBuffer html = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    html.append(inputLine);
                }
                in.close();

问题是,我在网上读到的所有内容都指向通过doGet或doPost重定向。我想通过execute()方法重定向

谢谢


共 (1) 个答案