【发布时间】:2020-12-17 19:50:25
【问题描述】:
我在 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);
【问题讨论】:
标签: java json ajax jsp servlets