首先要写一个jsp文件
<%@page pageEncoding="utf-8"
contentType="text/html;charset=utf-8"%>
<html>
<head>
<script type="text/javascript" src="js/my.js">
</script>
<script type="text/javascript" src="js/prototype-1.6.0.3.js">
</script>
<script type="text/javascript">
function getNum(){
var xhr = getXhr();
xhr.open('get','getNum.do?' + Math.random(),true);
xhr.onreadystatechange=function(){
if(xhr.readyState == 4){
var num = xhr.responseText;
$('d1').innerHTML = num;
}
};
xhr.send(null);
}
</script>
</head>
<body style="font-size:30px;">
<a href="javascript:;" onclick="getNum();">点击这儿,获得一个随机数</a>
<div id="d1" style="font-style:italic;"></div>
</body>
</html>
2其中涉及引入的js文件,可以下载获得
3 写一个servlet
package web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ActionServlet extends HttpServlet {
public void service(HttpServletRequest
request, HttpServletResponse response)
throws ServletException,
IOException {
response.setContentType
("text/html;charset=utf-8");
PrintWriter out = response.getWriter
();
String uri = request.getRequestURI();
String action = uri.substring
(uri.lastIndexOf("/"),
uri.lastIndexOf("."));
if(action.equals("/citys")){
String province =
request.getParameter("province");
if(action.equals("/getNum")){
Random r = new Random();
int num = r.nextInt(999);
System.out.println("num:" +
num);
out.println(num);
}
out.close();
}
}
4 部署在eclipse即可,运行jsp文件