I've been going crazy trying to figure out how to solve this issue. I have a servlet deployed in Tomcat running on localhost:8080 that looks like this:
@WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true)
public class CreateCon extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
ConcurrentHashMap<String, AsyncContext> map;
public CreateCon() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void init() {
map = new ConcurrentHashMap<>();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext context = request.startAsync(request,response);
context.setTimeout(10000);
if(!map.containsKey("Hello"))
map.put("Hello", context);
System.out.print("Inside GET");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext context = map.get("Hello");
PrintWriter writer = context.getResponse().getWriter();
writer.write(request.getParameter("message"));
writer.flush();
System.out.print(request.getParameter("message"));
}
}
Everything works fine when testing in Eclipse with Tomcat. The code is functioning as expected and I even added a System.out.print
to verify the functionality.
However, there seems to be an issue with the following javascript:
function postMessage(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "/SampleTest/createcon", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var messageText = escape(document.getElementById("i1").value);
document.getElementById("i1").value = "";
xmlhttp.send("message="+messageText);
}
The onreadystatechange
function is triggering as expected, but the xmlhttp.responseText
always returns blank.
I'm aware of the same-origin policy, but I'm confused why it's causing an issue here since everything is running on localhost:8080
.
Why is this happening and what can I do to fix it?