如何在浏览器而不是控制台中显示 servlet 提供的信息?

How to show information given by the servlet in the browser instead of the console?

我在 Eclipse 中制作了一个 servlet,并且 运行 它在 Tomcat 服务器上。 servlet 正在使用用户名和 apitoken 从 API 获取一些数据。

我做了一个文件index.jsp。它有一个导航栏和几个按钮。

现在我在 index.jsp 中单击一个按钮时调用 servlet。单击按钮 - 控制台显示 JSON 数据,在 Tomcat 上的浏览​​器 运行 上不显示任何数据。

理想情况下我希望浏览器在浏览器上显示JSON数据。有人能帮我写点代码吗?

这是我在 index.jsp 中调用服务器的按钮:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
      function callServlet() {
          document.forms[0].action = "testing";
          document.forms[0].submit();
      }
  </script>
</head>

<body>
..
.
.
<form id="WhatsNewFormID" name="WhatsNewForm" method="post">
  <div id="WhatsNewBtn"><input id="btn" type="submit" value="Hello World" style="float:right" class="w3-button w3-bar-item" onclick="callServlet();" /></div>
  </form>
  .
  .
  
 </body>

这是我的 servlet 的一部分:

String theUrl="TheURLForTheApiZZZ";
          URL url = new URL(theUrl);

// 创建一个 urlconnection 对象 URLConnection urlConnection = url.openConnection();

 String userpass = "usernameXXX" + ":" + "apitokenYYY; 
              String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
              urlConnection.setRequestProperty ("Authorization", basicAuth);
             
          
          // wrap the urlconnection in a bufferedreader
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

          String line;

          // read from the urlconnection via the bufferedreader
          while ((line = bufferedReader.readLine()) != null)
          {
            content.append(line + "\n");
          }
          bufferedReader.close();
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
        
     output= content.toString();
     System.out.println(output);

您没有将内容写入负责将内容发送到浏览器的响应对象 (HttpServletResponse response)。就在行 System.out.println(output) 之前,将以下代码放入您的 servlet 中:

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(output);

如果您不想在控制台上显示内容,只需删除该行,System.out.println(output);