Issue
I have a problem calling a servlet, so I need help.
Here is my web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ajaxServlet</servlet-name>
<servlet-class>org.finki.exercise.servlet.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajaxServlet</servlet-name>
<url-pattern>/ajaxServlet/*</url-pattern>
</servlet-mapping></servlet>
I have a jsp page for test purpose , where I amm trying to invoke servlet from ajax
<a href="#" onclick="loadXMLDoc('eva')">proba</a>
ajax fun
function loadXMLDoc(value1)
{
var xmlhttp;
var url="ajaxServlet";
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mid_title").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", url+"?url="+value1, true);
xmlhttp.send();
}
function loadXMLDoc invoke the dispatcher servlet http://localhost:8097/mavenproject1/test/ajaxServlet
.
How to invoke ajaxServlet - http://localhost:8097ajaxServlet
?
Solution
ajaxServlet
doesn't have a leading /
, therefore it's interpreted as a relative path. So if you send a request to ajaxServlet
from http://localhost:8097/mavenproject1/test/foo
, request will be sent to http://localhost:8097/mavenproject1/test/ajaxServlet
.
So, you need to add a leading /
. But it's not enough, because you also need to add context path of your application (/mavenproject1
). In JSP page you can do it automatically as follows (assuming that you imported JSTL tag library):
var url= "<c:url value = "ajaxServlet" />";
Answered By - axtavt
Answer Checked By - Willingham (JavaFixing Volunteer)