1.java代码如下:
package com.eduask;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//测试Ajax请求方式为post;
public class Demo3 extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//接受用户的输入的name;
String name=req.getParameter("name1");
if("tom".equals(name)){
resp.getWriter().write("<font color=red>该用户已经注册</font>");
}else{
resp.getWriter().write("<font color=blue>用户可以注册</font>");
}
}
}
2.demo3.jsp代码如下:
<%@ page language="java" contentType="text/html; utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ajax测试post请求方式</title>
</head>
<body>
请输入用户名: <input id="name1" type="text" name="name1">
<span id="span1"></span>
<script type="text/javascript">
var getName1Id=document.getElementById("name1");
getName1Id.οnblur=function(){
var xhr=getXhr();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
var msg=xhr.responseText;
var span1=document.getElementById("span1");
span1.innerHTML=msg;
}
}
}
xhr.open("post","/ajax/Demo3");
//设置消息头,告诉浏览器携带请求体数据;
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("name1="+getName1Id.value);
}
function getXhr(){
var xhr;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("microsoft,xmlhttp");
}
return xhr;
}
</script>
</body>
</html>
3.web.xml配置文件如下:
<!-- demo3 -->
<servlet>
<servlet-name>Demo3</servlet-name>
<servlet-class>com.eduask.Demo3</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo3</servlet-name>
<url-pattern>/Demo3</url-pattern>
</servlet-mapping>