Servlet部分
package cn.xdl.demo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
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 RandomValue
*/
@WebServlet("/random.do")
public class RandomValue extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RandomValue() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
Random random = new Random();
int r=random.nextInt(1000);
PrintWriter pw = response.getWriter();
pw.write(r+"");
pw.close();
}
}
//==================jsp部分
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.util.Date" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" >
function getRandom(){
$.ajax({
url:"random.do",
type:"post",
success:function(data){
$("#sp1").html(data);
}
});
}
</script>
</head>
<body>
<%=new Date() %>
<input type="button" value="获取随机数" οnclick="getRandom()"><br>
<span id="sp1"></span>
</body>
</html>