In TestAjax.java(Location:webapps/servlets/,is compiled):
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
String data = "Hello World";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
}
In HTML(JavaScript):
function showHelloWorld(inputForm) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '../../examples/servlets/TestAjax.class', true);
xhr.send(null);
}
In web.xml:
<servlet>
<servlet-name>TestAjax</servlet-name>
<display-name>TestAjax</display-name>
<servlet-class>TestAjax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestAjax</servlet-name>
<url-pattern>/servlet/TestAjax</url-pattern>
</servlet-mapping>
Symptom:
When showHelloWorld() is executed, the alert box shows this:
����2,
!()VCodeLineNumberTabledoGetR(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V Exceptions"# SourceFile TestAjax.java*Hello World* text/plain$%&UTF-8'&()*+&TestAjaxjavax/servlet/http/HttpServletjava/io/IOExceptionjavax/servlet/ServletException&javax/servlet/http/HttpServletResponsesetContentType(Ljava/lang/String;)VsetCharacterEncoding getWriter()Ljava/io/PrintWriter;java/io/PrintWriterwrite!
*�� FN,�,�,�-��?@ABC
Note there is "Hello World" in it, but the correct response should only have "Hello World", there shouldn't be all these craps in the response.
I've checked the code and deployment a million times, still found no clue.
Please shed some light on this problem, I would appreciate it very much!