I need to capture the response from the servlet in the jsp page using JavaScript. I have included the following code:
TestServlet.java:
package com.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
String testString = "Load Check";
//request.setAttribute("test", testString);
//request.getRequestDispatcher("").include(request, response);
response.getWriter().write("Test Success");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test JSP</title>
</head>
<body>
<script type="text/javascript">
function callServeltAndGetResponse(){
var servlet = new XMLHttpRequest();
servlet.onreadystatechange = function(){
var servletResponse = servlet.responseText;
document.getElementById("response").innerHTML = servletResponse;
}
servlet.open('GET','TestServlet',true);
}
</script>
<form onSubmit="javascript:callServletAndGetResponse()">
<input type=submit>
</form>
<div id="response"></div>
</body>
</html>
In the provided jsp page, the content of the div does not change even though the servlet generates a response. What could be causing this issue?