20:37:56
实现步骤:
1.首先创建一个html,里面写一个文本框和按钮
2.创建异步请求的核心对象
3.设置请求方式
4.设置结果产生的回调函数
5.获取异步请求对象
6.准备发送
7.写一个servlet,随机产生使用 UUID randomUUID = UUID.randomUUID();
8.注册数据,处理函数
9.获取返回的数据
10.将文本赋值给文本框
11.发送请求
代码演示:
html代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 <style type="text/css"> 7 *{ 8 margin: 2px; 9 padding: 2px; 10 } 11 input { 12 height: 30px; 13 } 14 #btn1{ 15 height: 38px; 16 } 17 #txt{ 18 width: 260px; 19 } 20 </style> 21 <script type="text/javascript"> 22 function getXHR() { 23 var xhr = null; 24 if(this.XMLHttpRequest){ 25 xhr = new XMLHttpRequest(); 26 }else{ 27 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 28 } 29 return xhr; 30 } 31 function UUIDRandom() { 32 //获取异步请求对象 33 var xhr = getXHR(); 34 //准备发送请求 35 xhr.open('post','random.do',true); 36 //注册数据,处理函数 37 xhr.onreadystatechange = function(){ 38 if(xhr.readyState == 4 && xhr.status == 200){ 39 //获取返回的数据 40 var text = xhr.responseText; 41 var oTxt = document.getElementById('txt'); 42 //把文本赋值给oTxt对象 43 oTxt.value = text; 44 } 45 }; 46 //发送请求 47 xhr.send(null); 48 } 49 </script> 50 </head> 51 <body> 52 <input id="txt" type="text" value=""> 53 <input id="btn1" type="button" value="获取序列码" onclick="UUIDRandom()"> 54 </body> 55 </html>
java代码:
1 package com.xcz.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.UUID; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class UUIDRandom 15 */ 16 @WebServlet("/random.do") 17 public class UUIDRandom extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 20 UUID randomUUID = UUID.randomUUID(); 21 System.out.println(randomUUID); 22 PrintWriter pw = response.getWriter(); 23 pw.println(randomUUID); 24 } 25 }