00 01 Ajax learning II of Java Web

Article directory

1 ajax first example: helloworld

Server code:

package org.lks.servlet;

import java.io.IOException;
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 MyServlet
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/MyServlet" })
public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Hello Ajax");
		response.getWriter().print("Hello Ajax!!!");
	}

}

Client jsp code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hello world</title>
<script>
function createXMLHttpRequest(){
	try{
		return new XMLHttpRequest();
	}catch(e){
		try{
			return ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				return ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				alert("What!!!");
				throw e;
			}
		}
	}
}

window.onload = function(){
	var btn = document.getElementById("btn");
	btn.onclick = function(){
		//ajax four step operation
		var xmlHttp = createXMLHttpRequest();
		
		xmlHttp.open("GET", "MyServlet", true);
		
		xmlHttp.send(null);

		xmlHttp.onreadystatechange = function(){
			if( xmlHttp.readyState == 4 && xmlHttp.status == 200){
				var text = xmlHttp.responseText;
				var h1 = document.getElementById("h1");
				h1.innerHTML = text;
			}
		}
		 
	}
}
</script>
</head>
<body>
	<button id="btn">click on!</button>
	<h1 id="h1"></h1>
</body>
</html>

2 ajax second example: send POST request

(1)open: xmlHttp.open("POST",...);
(2) Add one step: set content type request header
|-xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded);
(3) send: xmlhttp. send ("username = LKS & & password = HHY"); specify the request body when sending the request

js code of client page:

window.onload = function(){
	var btn = document.getElementById("btn");
	btn.onclick = function(){
		//ajax four step operation
		var xmlHttp = createXMLHttpRequest();
		
		xmlHttp.open("POST", "MyServlet", true);
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		
		xmlHttp.send("username=Luo Kai Sheng&&password=123");

		xmlHttp.onreadystatechange = function(){
			if( xmlHttp.readyState == 4 && xmlHttp.status == 200){
				var text = xmlHttp.responseText;
				var h1 = document.getElementById("h1");
				h1.innerHTML = text;
			}
		}
		 
	}
}

Server code:

package org.lks.servlet;

import java.io.IOException;
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 MyServlet
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/MyServlet" })
public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Hello Ajax");
		response.getWriter().print("Hello Ajax!!!");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		String username = req.getParameter("username");
		System.out.println("Hello Ajax!!!" + username);
		resp.getWriter().print("Hello Ajax!!!" + username);
	}
	
	

}

3 ajax example 3: whether the user name is registered

1. Write page: username.jsp
(1) Give registration form page
(2) Add onblur event listening to the user name text box
(3) Get the content of the text box and send it to the server through ajax4 steps to get the response result
|-- if it is 1, "user name registered" will be displayed after the text box
|-- buy shares for 0: do nothing
2. Write Servlet: ValidateUsernameServlet
(1) Get the user name parameter passed by the client
(2) Judge whether it exists: Yes returns 1, otherwise 0.

Page code:

<body>
<h1>User registration</h1>
<form action="" method="post">
Username: <input type="text" name="username" id="usernameEle"/><span id="ajaxinfo"></span><br>
Password: <input type="text" name="password" id="passwordEle"/><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>

js code:

<script>
function createXMLHttpRequest(){
	try{
		return new XMLHttpRequest();
	}catch(e){
		try{
			return ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				return ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				throw e;
			}
		}
	}
};

window.onload = function(){
	var user = document.getElementById("usernameEle");
	user.onblur = function(){
		var xmlHttp = createXMLHttpRequest();
		//alert("create ok");
		xmlHttp.open("POST", "SignUpServlet", true);
		//alert("open ok");
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlHttp.send("username=" + user.value);
		//alert("send ok");
		xmlHttp.onreadystatechange = function(){
			//alert("onready ok");
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				var res = xmlHttp.responseText;
				var span = document.getElementById("ajaxinfo");
				if(res == "1"){
					span.innerHTML = "User name registered";
				}else{
					span.innerHTML = "";
				}
				
			}
		};
	};
};


</script>

Server code:

package org.lks.servlet;

import java.io.IOException;
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 SignUpServlet
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/SignUpServlet" })
public class SignUpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String username = request.getParameter("username");
		if("lks".equals(username)) {
			response.getWriter().print("1");
		}else {
			response.getWriter().print("0");
		}
	}

}

4 ajax example 4: the response content is xml

1. Server side
(1) Set response header: content type, with value: text/xml;charset=utf-8
2. Client
(1) var doc = xmlHttp.responseXML; the result is a Document object
Page JS code:

<script>
function createXMLHttpRequest(){
	try{
		return new XMLHttpRequest();
	}catch(e){
		try{
			return ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				return ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				throw e;
			}
		}
	}
};


window.onload = function(){
	var xmlHttp = createXMLHttpRequest();
	xmlHttp.open("GET", "XMLServlet", true);
	xmlHttp.send(null);
	xmlHttp.onreadystatechange = function(){
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
			var xml = xmlHttp.responseXML;
			var stu = xml.getElementsByTagName("student")[0];
			var id = stu.getAttribute("id");
			if(window.addEventListener){
				var name = stu.getElementsByTagName("name")[0].firstChild.nodeValue;
				var age = stu.getElementsByTagName("age")[0].firstChild.nodeValue;
			}else{
				var name = stu.getElementsByTagName("name")[0].firstChild.nodeValue;
				var age = stu.getElementsByTagName("age")[0].firstChild.nodeValue;
			}
			
			var info = id+ ", " + name + ", " + age;
			document.getElementById("h1").innerHTML = info;
		}
	};
};
</script>

Page code:

<body>
<h1 id="h1"></h1>
</body>

Server code:

package org.lks.servlet;

import java.io.IOException;
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 XMLServlet
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/XMLServlet" })
public class XMLServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String xml = "<students>" +
				"<student id='3161301220'>" + 
				"<name>lks</name>" +
				"<age>23</age>" +
				"</student>" +
				"</students>";
		
		resp.setContentType("text/xml;charset=utf-8");
		resp.getWriter().print(xml);
	}

	

}

5 the fifth example of Ajax: provincial and municipal linkage

1, page

<select name="province">
    <option>===Select provinces===</option>
</select>
<select name="city">
    <option>===Choice of city===</option>
</select>

2,ProvinceServlet
(1) ProvinceServlet: request this Servlet as soon as the page is loaded.
|-- it needs to load the chinaprovince.xml file and send the names of all provinces to the client using strings.
3. Page work
(1) Get this string, separated by commas, get the array
(2) Loop through each string (the name of the province), using each string to create an < option > element to add to the < select name = "province" > element.
4,CityServlet
(1) CityServlet: send the request when the page selects a time-saving.
(2) Get the name of the province, load the china.xml file, query the element object corresponding to the province, convert the element into an XML string, and send it to the client.
5. Page work
(1) Delete all child elements in < select name = "city" >
(2) Get server response results
(3) Get all the < City > sub elements, loop through them, and get the content of < City >
(4) Create an < option > element with each < City > content and add it to < select name = "city" >
Page code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Province and City</title>
<script>
function createXMLHttpRequest(){
	try{
		return new XMLHttpRequest();
	}catch(e){
		try{
			return ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				return ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				throw e;
			}
		}
	}
};

window.onload = function(){
	var select = document.getElementsByTagName("select")[0];
	var xmlHttp = createXMLHttpRequest();
	xmlHttp.open("GET", "ProServlet", true);
	xmlHttp.send(null);
	xmlHttp.onreadystatechange = function(){
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
			var text = xmlHttp.responseText;
			var list = text.split(",");
			for(var i = 0; i < list.length; i++){
				var op = document.createElement("option");
				var optext = document.createTextNode(list[i]);
				op.appendChild(optext);
				select.appendChild(op);
			}
			
		}
	}
	
	var pro = document.getElementById("pro");
	pro.onchange = function(){
		xmlHttp.open("POST", "CityServlet", true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.send("province=" + pro.value);
		xmlHttp.onreadystatechange = function(){
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				var text = xmlHttp.responseText;
				var city = document.getElementById("cit");
				var citys = text.split(",");
				var options = city.getElementsByTagName("option");
				while(options.length > 1){
					city.removeChild(options[1]);
				}
				for(var i = 0; i < citys.length; i++){
					var op = document.createElement("option");
					var optext = document.createTextNode(citys[i]);
					op.appendChild(optext);
					city.appendChild(op);
				}
			}
		}
	}
}
</script>
</head>
<body>
<select name="province" id="pro">
    <option>===Select provinces===</option>
</select>
<select name="city" id="cit">
    <option>===Choice of city===</option>
</select>
</body>
</html>

Server code:

package org.lks.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 * Servlet implementation class CityServlet
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/CityServlet" })
public class CityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @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
		//String pro = request.getParameter("province");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String provin = request.getParameter("province");
		System.out.println(provin);
		
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read("D:/code_learn/java/javaee/project/ajaxlearn/src/chinapro.xml");
			List<Node> list = document.selectNodes("//province[@name=\"" + provin + "\"]/city");
			System.out.println(list.size());
			StringBuilder sbd = new StringBuilder();
			for(int i = 0; i < list.size(); i++) {
				sbd.append(list.get(i).getText());
				if(i < list.size() - 1) {
					sbd.append(",");
				}
			}
			System.out.println(sbd);
			response.getWriter().print(sbd);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}

Server code:

package org.lks.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 * Servlet implementation class ProServlet
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/ProServlet" })
public class ProServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		try {
			SAXReader saxReader = new SAXReader();
			InputStream input = new FileInputStream("D:/code_learn/java/javaee/project/ajaxlearn/src/chinapro.xml");
			Document document = saxReader.read(input);
			List<Node> list = document.selectNodes("//province/@name");
			StringBuilder str = new StringBuilder();
			for(int i = 0; i < list.size(); i++) {
				str.append(list.get(i).getText());
				if(i < list.size() - 1) {
					str.append(",");
			}
			}
			System.out.println(str);
			response.getWriter().print(str);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}

	/**
	 * @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);
	}

}

Published 85 original articles, won praise 11, visited 2829
Private letter follow

Tags: Java xml JSP JavaEE

Posted on Wed, 11 Mar 2020 03:52:18 -0400 by busnut