Issue
I have made a servlet in Eclipse and am running it on Tomcat server. The servlet is getting some data from an API using username and apitoken.
I have made an file namely index.jsp. It has a navigation bar and few buttons.
Now I am calling the servlet when clicking one button in my index.jsp. On click of the button- the console displays the JSON data and nothing on the browser running on Tomcat.
Ideally I want the browser to display the JSON data on the browser. Would anybody be able to help me with some coding?
This is my button calling the server in 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>
And this is a part of my servlet:
String theUrl="TheURLForTheApiZZZ";
URL url = new URL(theUrl);
// create a urlconnection object 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);
Solution
You have missed writing the content to the response object (HttpServletResponse response
) which is responsible for sending the content to the browser. Just before the line, System.out.println(output)
, put the following code in your servlet:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(output);
If you do not want to display the content on the console, simply remove the line, System.out.println(output);
Answered By - Arvind Kumar Avinash
Answer Checked By - Mildred Charles (JavaFixing Admin)