1.JSON(格式要正确,可以引jar包操作)
servlet代码
package com.hsp.action; import java.io.IOException;
import java.io.PrintWriter; import javax.json.JsonString;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class showCities
*/
@WebServlet("/showCities")
public class showCities extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public showCities() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/xml;charset=utf-8");
response.setHeader("Cache-Control", "no-cache"); //接收用户选择的省的名字
String shengString=request.getParameter("province");
System.out.println(shengString);
PrintWriter out=response.getWriter();
StringBuilder builder=new StringBuilder(); String info=""; // if ("zhejiang".equals(shengString)) {
// System.out.println("浙江");
// info="<province><city>杭州</city><city>温州</city><city>宁波</city></province>";
// }
// else if ("jiangsu".equals(shengString)) {
// System.out.println("江苏");
//
// info="<province><city>南京</city><city>徐州</city><city>苏州</city></province>";
// }
if ("zhejiang".equals(shengString))
{
info= "[{"+'"'+"city"+'"'+":"+'"'+"杭州"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"温州"+'"'+"}]";
}
else if ("jiangsu".equals(shengString)) {
info= "[{"+'"'+"city"+'"'+":"+'"'+"南京"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"苏州"+'"'+"}]"; }
System.out.println("{"+'"'+"ins"+'"'+":"+info+"}");
builder.append("{"+'"'+"ins"+'"'+":"+info+"}"); out.println(builder.toString());
} }
jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'Mycity.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<script type="text/javascript">
//1.创建ajax引擎
function getXmlHttpObject(){
var xmlHttpRequest;
//不同的浏览器获取对象xmlhttprequest对象方法不一样
if(window.ActiveXobject)
{
xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP");
}
else
{
xmlHttpRequest=new XMLHttpRequest();
}
return xmlHttpRequest;
} //新建myXmlHttpRequest对象
var myXmlHttpRequest=""; function getCities(){
//创建对象
myXmlHttpRequest=getXmlHttpObject();
// window.alert(myXmlHttpRequest);
//如果创建成功,则进行post请求
if(myXmlHttpRequest){
//创建url
var url="/ajax/showCities";//post
//携带的参数
var data="province="+$('sheng').value;
//
myXmlHttpRequest.open("post",url,true);
//必填
myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//指定回调函数
myXmlHttpRequest.onreadystatechange=chuli;
//发送请求
myXmlHttpRequest.send(data); } } function chuli(){
if(myXmlHttpRequest.readyState==4){
var mes= myXmlHttpRequest.responseText;
window.alert(mes);
var mes_obj=eval("("+mes+")");
window.alert(mes_obj);
window.alert(mes_obj.ins[0].city);
// $('myres').value=mes_obj.info; //取出xml格式数据
/* if(myXmlHttpRequest.status==200)
{
//取出服务器回送的数据
window.alert(myXmlHttpRequest.responseXML);
var cities= (myXmlHttpRequest.responseXML.getElementsByTagName("city"));
//window.alert(cities.length);
//alert(cities[1].lastChild.nodeValue);
for(var i=0;i<cities.length;i++)
{alert(cities[i].childNodes[0].nodeValue);}
} */ } } function $(id)
{
return document.getElementById(id);
} </script> This is my JSP page. <br> <select id="sheng" onchange="getCities();">
<option value="">---省---</option>
<option value="zhejiang">浙江</option>
<option value="jiangsu">江苏</option>
</select> <select id="city" onchange="sendRequest();">
<option value="">--城市--</option>
</select> <select id="country" onchange="sendRequest();">
<option value="">--县城--</option>
</select> </body>
</html>
2.xml格式
servlet代码
package com.hsp.action; import java.io.IOException;
import java.io.PrintWriter; import javax.json.JsonString;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class showCities
*/
@WebServlet("/showCities")
public class showCities extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public showCities() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/xml;charset=utf-8");
response.setHeader("Cache-Control", "no-cache"); //接收用户选择的省的名字
String shengString=request.getParameter("province");
System.out.println(shengString);
PrintWriter out=response.getWriter();
StringBuilder builder=new StringBuilder(); String info=""; if ("zhejiang".equals(shengString)) {
System.out.println("浙江");
info="<province><city>杭州</city><city>温州</city><city>宁波</city></province>";
}
else if ("jiangsu".equals(shengString)) {
System.out.println("江苏"); info="<province><city>南京</city><city>徐州</city><city>苏州</city></province>";
}
// if ("zhejiang".equals(shengString))
// {
// info= "[{"+'"'+"city"+'"'+":"+'"'+"杭州"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"温州"+'"'+"}]";
// }
// else if ("jiangsu".equals(shengString)) {
// info= "[{"+'"'+"city"+'"'+":"+'"'+"南京"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"苏州"+'"'+"}]";
//
// }
// System.out.println("{"+'"'+"ins"+'"'+":"+info+"}");
// builder.append("{"+'"'+"ins"+'"'+":"+info+"}");
builder.append(info);
out.println(builder.toString());
} }
jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'Mycity.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<script type="text/javascript">
//1.创建ajax引擎
function getXmlHttpObject(){
var xmlHttpRequest;
//不同的浏览器获取对象xmlhttprequest对象方法不一样
if(window.ActiveXobject)
{
xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP");
}
else
{
xmlHttpRequest=new XMLHttpRequest();
}
return xmlHttpRequest;
} //新建myXmlHttpRequest对象
var myXmlHttpRequest=""; function getCities(){
//创建对象
myXmlHttpRequest=getXmlHttpObject();
// window.alert(myXmlHttpRequest);
//如果创建成功,则进行post请求
if(myXmlHttpRequest){
//创建url
var url="/ajax/showCities";//post
//携带的参数
var data="province="+$('sheng').value;
//
myXmlHttpRequest.open("post",url,true);
//必填
myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//指定回调函数
myXmlHttpRequest.onreadystatechange=chuli;
//发送请求
myXmlHttpRequest.send(data); } } function chuli(){
if(myXmlHttpRequest.readyState==4){
// var mes= myXmlHttpRequest.responseText;
/* window.alert(mes);
var mes_obj=eval("("+mes+")");
window.alert(mes_obj);
window.alert(mes_obj.ins[0].city); */
// $('myres').value=mes_obj.info; //取出xml格式数据
if(myXmlHttpRequest.status==200)
{
//取出服务器回送的数据
window.alert(myXmlHttpRequest.responseXML);
var cities= (myXmlHttpRequest.responseXML.getElementsByTagName("city"));
//window.alert(cities.length);
//alert(cities[1].lastChild.nodeValue);
for(var i=0;i<cities.length;i++)
{alert(cities[i].childNodes[0].nodeValue);}
} } } function $(id)
{
return document.getElementById(id);
} </script> This is my JSP page. <br> <select id="sheng" onchange="getCities();">
<option value="">---省---</option>
<option value="zhejiang">浙江</option>
<option value="jiangsu">江苏</option>
</select> <select id="city" onchange="sendRequest();">
<option value="">--城市--</option>
</select> <select id="country" onchange="sendRequest();">
<option value="">--县城--</option>
</select> </body>
</html>
3.text格式
servlet 格式
package com.hsp.action; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class registerServlet
*/
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public registerServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub //接受数据
//String username=request.getParameter("username");
//System.out.println(username);
String infoString="";
if ("shunping".equals("")) {
infoString="用户名不可用";
}
else {
infoString="用户名可用"; }
//返回文本数据
// response.setContentType("text/;charset=utf-8");
//返回xml格式文件
response.setContentType("text/xml;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); //返回xml 格式数据
PrintWriter out=response.getWriter();
StringBuilder builder=new StringBuilder();
// builder.append("<message>");
// builder.append(infoString).append("</message>"); // builder.append( "{"+'"'+"info"+'"'+":" ).append('"'+infoString+'"'+"}");
builder.append(infoString);
out.println(builder.toString()); //返回text格式数据
// ServletOutputStream outputStream = response.getOutputStream();
// outputStream.write(infoString.getBytes("utf-8"));
// //outputStream.write(pwd.getBytes("utf-8"));
// outputStream.flush();
// outputStream.close();
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
jsp格式
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<script type="text/javascript"> //创建ajax引擎
function getXmlHttpObject(){
var xmlHttpRequest;
//不同的浏览器获取对象xmlhttprequest对象方法不一样
if(window.ActiveXobject)
{
xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP");
}
else
{
xmlHttpRequest=new XMLHttpRequest();
}
return xmlHttpRequest;
} var myXmlHttpRequest=null;
//验证用户名是否存在
function checkName()
{ myXmlHttpRequest=getXmlHttpObject(); // window.alert(myXmlHttpRequest); if(myXmlHttpRequest ){
// window.alert("创建成功");
//通过myXmlHttpRequest对象发送请求到服务器的某个页面
//1.第一个参数表示请求的方式,"get"/"post"
//2.第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求)
//3.第三个参数 true表示使用异步机制,如果false,表示不使用异步
var url="/ajax/registerServlet?mytime="+new Date()+"&username="+$("username").value
//打开请求
myXmlHttpRequest.open("post",url,true);
//window.alert(url);
//指定回调函数,chuli 是函数名
myXmlHttpRequest.onreadystatechange=chuli;
//真的发送函数,如果是get请求,则填入null即可
//如果是post请求,则填入实际的数据
myXmlHttpRequest.send(null); } } //回调函数
function chuli(){
//window.alert("处理函数被调用"+myXmlHttpRequest.readyState);
//取出从serlet返回的数据
if(myXmlHttpRequest.readyState==4)
{
//取出值,文本格式
//window.alert("服务器返回"+myXmlHttpRequest.responseText)
//
//window.alert( "xml:"+myXmlHttpRequest.responseXML);
//获取message节点
// var mes=myXmlHttpRequest.responseXML.getElementsByTagName("message");
//window.alert(mes.length);
//取出message节点
//es[0]-->表示取出第一个message节点
//childNodes[0]表示message节点的第一个子节点
// var mes_val=mes[0].childNodes[0].nodeValue;
//window.alert(mes_val);
// ${'myres'}.value= mes_val;
//$('myres').value=myXmlHttpRequest.responseText;
/* var mes= myXmlHttpRequest.responseText;
window.alert(mes);
var mes_obj=eval("("+mes+")");
//window.alert(mes_obj.info);
$('myres').value=mes_obj.info;
*/
var mes= myXmlHttpRequest.responseText; $('myres').value=mes; }
} function $(id)
{
return document.getElementById(id);
} </script> This is my JSP page. <br>
<form action="???" method="post"> 用户名:<input type="text"name="username1" onkeyup="checkName();" id="username">
<input type="button" onclick="checkName();" value="验证用户名">
<input style="border-width: 0;color: red" type="text" id="myres"><br>
用户密码:<input type="password" name="password"><br>
电子邮件:<input type="text" name="email"><br>
<input type="submit" value="用户注册">
</form> </body>
</html>