在java中执行JSP



我正试图通过建立URL连接在本地机器上执行JSP,但我似乎无法执行它,我认为可能是java找不到JSP,但似乎找不到原因,因为JSP的URL看起来很好,有人知道它为什么不执行吗?我的代码片段和webapp结构如下。

谢谢。

       URL url = new URL("http://127.0.0.1/folder1/folder2/folder3/test.jsp");
       URLConnection connection = url.openConnection();
       connection.setDoOutput(true);
       OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
       out.write("id=" + id);
       out.close();
       BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
       String output;
       StringBuilder sb = new StringBuilder();
       boolean started = false;
       while ((output = in.readLine()) != null) {
           if (!output.trim().equals("")) {
                started = true;
           }
            if (started) {
                sb.append(output);
                sb.append("rn");
            }
        }
        in.close();
        System.out.println(sb.toString());

我的Web应用程序具有与以下类似的结构。

 webapp
    /WEB-INF
         /classes
         web.xml
    /folder1
       /folder2
          /folder3
             test.jsp

我认为您可能打算执行以下操作(不包括输出部分):

URL url = new URL("http://127.0.0.1/folder1/folder2/folder3/test.jsp?id=" + id);

output使用StringBuilder,效率会高得多。


text.jsp应该同时执行这两项操作:在表单中请求id并处理表单,然后执行而不是使用:

if (request.getMethod().equals("POST")) {
    String id = request.getParameter("id");
    ... handle given id
    return;
}
... show form

但是使用GET/POST不可知/不相关的代码:

String id = request.getParameter("id");
if (id != null) {
    ... handle given id
    return;
}
... show form

这样您正在执行的HTTPGET就可以正常工作了。

我认为您缺少应用程序名称。如果您在tomcat中运行应用程序,则默认端口为8080。

http://127.0.0.1:<port>/<web-app-name>/folder1/folder2/folder3/test.jsp

我在下面给出了一种故障排除方法,因为我对您收到的故障消息不太了解。

  1. 我会尝试访问其他网页,而不是您的URL假如只是为了证明您的URLConnection方法是正确的这是访问JSP文件的问题。

  2. 查看您的请求返回的实际消息/页面。是404页吗?如果是这样,那么你的URL是关闭的。

  3. 并确保您可以直接在浏览器中访问该URL。

问题是由于从**http**://localhost/folder1/folder2/folder3/test.jsp重定向到**https**://localhost/folder1/folder2/folder3/test.jsp,当我在浏览器中打开JSP时,这不是最容易发现的重定向。非常烦人的是url。openConnection()似乎什么都没发生。

最新更新