Using AJAX -- can't find servlet -- Error 404
Hi,
I'm trying to get a simple AJAX application to run. I'm using the sample code provided by sun @ http://java.sun.com/developer/technicalArticles/J2EE/AJAX/index.html?cid=59754
For some reason it has a problem with theif (req.status == 200)
code. I have an alert message that pops up if that if condition isn't true and it returns Error: 404, or "Not found". In my JS I point to the Servlet just like they did in their example:
var url ="responder?id=" + escape(idField.value);
Responder is the name of the servlet and it's in the package:package xml_Response_Servlet;
All of the code is pasted below. I've even looked at other examples @ https://bpcatalog.dev.java.net/nonav/ajax/autocomplete/frames.html but I just can't figure out how to get the JS to "find" my Respond servlet.
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet"
type="text/css">
<TITLE>login.html</TITLE>
<script src="JS/XML_Script_1.js"></script>
</HEAD>
<BODY>
<input type="text"
size="20"
id="userid"
name="id"
onkeyup="validate();"/>
<div id="userIdMessage"></div>
</BODY>
</HTML>
package xml_Response_Servlet;
import java.util.HashMap;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
publicclass Responderextends HttpServlet
{
private ServletContext context;
private HashMap users =new HashMap();
publicvoid init(ServletConfig config)throws ServletException
{
this.context = config.getServletContext();
users.put("greg","account data");
users.put("duke","account data");
}
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException
{
String targetId = request.getParameter("id");
try
{
if ((targetId !=null) && !users.containsKey(targetId.trim()))
{
response.setContentType("text/xml");
response.setHeader("Cache-Control","no-cache");
response.getWriter().write("<message>"+"valid"+"<message>");
}
else
{
response.setContentType("text/xml");
response.setHeader("Cache-Control","no-cache");
response.getWriter().write("<message>"+"invalid"+"<message>");
}
}
catch( Exception E)
{System.out.println("Error! "+ E.getMessage());}
}
}
var req;
var message;
function validate()
{
var idField = document.getElementById("userid");
var url ="responder?id=" + escape(idField.value);
if (window.XMLHttpRequest)
{
req =new XMLHttpRequest();
}
elseif (window.ActiveXObject)
{
req =new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url,true);
req.onreadystatechange = callback;
req.send(null);
}
function callback()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
mdiv = document.getElementById("userIdMessage");
if (req.responseXML.getElementsByTagName("message")[0] =="invalid")
{
mdiv.innerHTML ="<div style=\"color:red\">Invalid User Id<>";
}
else
{
mdiv.innerHTML ="<div style=\"color:green\">Valid User Id<>";
}
}
else{alert("inner"+req.status)}
}
//else{alert("outer"+req.readyStat)}
}
//function parseMessage()
//{
//message = req.responseXML.getElementsByTagName("message")[0];
//setMessage(message.childNodes[0].nodeValue);
//}
Thanks in advance for any help.
- LS6V
[7947 byte] By [
ls6va] at [2007-10-2 6:37:12]

> var url = "responder?id=" + escape(idField.value);If the name of the servlet is Responder then put Responder in that URL and not responder.
Did that already. I'm trying everything because when I used JSF a method like getName would be called name in the JSP file, I still don't know why.
I've copying their code line for line and it won't work. I get the 404 status. But ithe server ready state is fine ( it equals 4 ).
My directory structure:
- Project Name
+ JavaSource
1. package
a. Responder.java
+ webcontent
1. JS
a. script1.js
2. Meta-INF
3. Web-INF
a. web.xml
4. login.html
for some reason there's a communication problem between my JS and my servlet class and I've spent the last couple of hours moving things, changin things and trying other similiar examples on the web. I continue to have the same problem.
ls6va at 2007-7-16 13:39:46 >

Where is the servlet .class file under WEB-INF? Should be in WEB-INF/classes/xml_Response_Servlet/Responder.class, right?
Your .java file should not be part of the web deployment.
You did compile the .java file, didn't you?
You didn't post your web.xml - maybe it's not correct.
What URL did you give to access the servlet?
Are you deploying in a WAR file? You should be.
%
> Where is the servlet .class file under WEB-INF?
> Should be in
> n
> WEB-INF/classes/xml_Response_Servlet/Responder.class,
> right? YES, it is
>
> Your .java file should not be part of the web
> deployment.
>
> You did compile the .java file, didn't you? YES
>
> You didn't post your web.xml - maybe it's not
> correct.> Forgot
> What URL did you give to access the servlet?
> var url = "Responder?id=" + escape(idField.value);
>req.open("GET", url, true);> Are you deploying in a WAR file? You should be. NO just testing it in WSAD 5.0
>
> %
I was checking things in the web xml but I couldn't find anything to really change. I did come across the options:
Automatic Request Encoding and Automatic Response Encoding. I enabled both but nothing changed so I disabled them again.
Web XML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp">
<display-name>Dec_1_AJAX</display-name>
<servlet>
<servlet-name>Responder</servlet-name>
<display-name>Responder</display-name>
<servlet-class>xml_Response_Servlet.Responder</servlet-class>
</servlet>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.php</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/application-1.0</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-application.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/page-1.0</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-page.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/request-1.0</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-request.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/response-1.0</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-response.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/session-1.0</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-session.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>jspsql</taglib-uri>
<taglib-location>/WEB-INF/lib/jspsql.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/datetime-1.0</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-datetime.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/string-1.0.1</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-string.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/utility</taglib-uri>
<taglib-location>/WEB-INF/lib/utility.jar</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/mailer-1.1</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-mailer.jar</taglib-location>
</taglib>
</web-app>
ls6va at 2007-7-16 13:39:46 >

So where's the servlet-mapping in the web.xml?<servlet-mapping><servlet-name>Responder</servlet-name><url-pattern>/Responder</url-pattern></servlet-mapping>%
> So where's the servlet-mapping in the web.xml?
>
> ><servlet-mapping>
> <servlet-name>Responder</servlet-name>
> <url-pattern>/Responder</url-pattern>
></servlet-mapping>
>
>
> %
.... thanks, I'm not familiar with making servlets. It finds the servlet but theres a problem with my JS logic because it always prints out that a valid user name was entered.
Thanks again, ls6v
ls6va at 2007-7-16 13:39:46 >

I added an alert and it say the value being returned is null. alert(req.responseXML.getElementsByTagName("message")[0]);Any idea why it isn't picking up the value from the servlet?
ls6va at 2007-7-16 13:39:46 >

Got it! They had a typo or mistake in their Java class.
They put a "!" in a if condition but ti shouldn't be there. Once I removed it the program is working correctly. Thanks again for the servlet hlep.
The working code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet"
type="text/css">
<TITLE>login.html</TITLE>
<script src="JS/XML_Script_1.js"></script>
</HEAD>
<BODY>
<input type="text"
size="20"
id="userid"
name="id"
onkeyup="validate();"/>
<div id="userIdMessage"></div>
</BODY>
</HTML>
JS
var req;
var message;
function validate()
{
var idField = document.getElementById("userid");
var url = "Responder?id=" + escape(idField.value);
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url, true);
req.onreadystatechange = callback;
req.send(null);
}
function callback()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
mdiv = document.getElementById("userIdMessage");
alert(req.responseXML.getElementsByTagName("message")[0].childNodes[0].nodeValue);
if (req.responseXML.getElementsByTagName("message")[0].childNodes[0].nodeValue == "invalid")
{
mdiv.innerHTML = "<div style=\"color:red\">Invalid User Id<>";
}
else
{
mdiv.innerHTML = "<div style=\"color:green\">Valid User Id<>";
}
}
else{alert("inner"+req.status)}
}
//else{alert("outer"+req.readyStat)}
}
//function parseMessage()
//{
//message = req.responseXML.getElementsByTagName("message")[0];
//setMessage(message.childNodes[0].nodeValue);
//}
JAVA servlet
package xml_Response_Servlet;
import java.util.HashMap;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Responder extends HttpServlet
{
private ServletContext context;
private HashMap users = new HashMap();
public void init(ServletConfig config) throws ServletException
{
this.context = config.getServletContext();
users.put("greg","account data");
users.put("duke","account data");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
String targetId = request.getParameter("id");
try
{
if ((targetId != null) && users.containsKey(targetId.trim()))
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<message>valid</message>");
}
else
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<message>invalid</message>");
}
}
catch( Exception E)
{System.out.println("Error! "+ E.getMessage());}
}
}
ls6va at 2007-7-16 13:39:46 >

> Got it! They had a typo or mistake in their Java
> class.
>
> They put a "!" in a if condition but ti shouldn't be
> there. Once I removed it the program is working
> correctly. Thanks again for the servlet hlep.
The terseness of the "!" operator is a very nasty problem inherited from C/C++.
It's almost invisible for mere human beings.
Some verboseness would be welcome - C has a #include file <iso646.h> that redefines the word "not" as "!", but Java has not such a thing.
C
#include <stdio.h>
#include <iso646.h>
main (int argc, char *argv[]) {
if (not (argc == 2) ) { // you can't deny that there's a "not" here!
printf ("Wrong number of parameters!\n");
}
}
Java
[code]
class Test {
public static void main(String[] args) {
if (! (args.length == 2) ) { // you almost missed the "!"
System.out.println ("Wrong number of parameters!");
}
}
}
[code]