HelloWorld.jsp
HelloWorld.java
[i][b]很简单的一个实例,大家用的时候要注意的是:
记得关闭缓存[/b][/i]
<%@ page contentType="text/html;charset=utf-8" language="java" errorPage="" %>
<html>
<head>
<meta http-equiv="pragma"content="no-cache">
<meta http-equiv="cache-control"content="no-cache,must-revalidate">
<meta http-equiv="expires"content="0">
<title>Ajax</title>
<script type="text/javascript">
function ok(){
var xmlhttp;
if(window.XMLHttpRequest){
//非IE
xmlhttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
}
}
xmlhttp.onreadystatechange=function(){
if(4==xmlhttp.readystate){
if(200==xmlhttp.status){
//获取返回值
var msgWelcome=xmlhttp.responseText;
var msg = document.getElementById("msg");
msg.innerHTML=msgWelcome;
}
}
}
//设定请求
xmlhttp.open("get","http://localhost:8080/Ajax/HelloWorld.do",true);
//设定http头
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
xmlhttp.send(null);
}
</script>
</head>
<body>
<span id="msg"></span>
<br>
<input type="button" onclick="ok();" value="单击此按钮" />
</body>
</html>
HelloWorld.java
package com.cn.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 463701915463621765L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=utf-8");
//无缓存
response.addHeader("pragma", "no-cache");
response.addHeader("cache-control", "no-cache,must-revalidate");
response.addHeader("expires", "0");
PrintWriter out=response.getWriter();
out.write("当前的系统时间是:"+getCurrentDateAndTime()+"欢迎(HelloWorld)");
}
private String getCurrentDateAndTime() {
// TODO Auto-generated method stub
String currentDate="";
//设定时间格式
SimpleDateFormat format=new SimpleDateFormat("yyyy'-'MM'-'dd HH:mm:ss");
format.setLenient(false);
currentDate=format.format(new Date());
//返回当前日期
return currentDate;
}
}
[i][b]很简单的一个实例,大家用的时候要注意的是:
记得关闭缓存[/b][/i]
response.addHeader("pragma", "no-cache");
response.addHeader("cache-control", "no-cache,must-revalidate");
response.addHeader("expires", "0");