springmvc+ajax——第二讲(页面缓存)
springmvc+ajax+页面缓存(参考:https://www.cnblogs.com/liuling/archive/2013/07/25/2013-7-25-01.html)
必须设置响应头才能实现页面缓存效果,一般对css等静态文件可以使用缓存,但是对于动态则不能使用缓存,springmvc默认是无缓存的。如果要想设置成有缓存,修改controller类:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class TestController {
public TestController() {
System.out.println("------TestController------");
}
@RequestMapping(value="/testAjax",method=RequestMethod.GET)//m //如果在前端alert("xxx")能执行通,但是后台没反应可能是 //method错了:ethod=RequestMethod.GET
public void testAjax(HttpServletRequest req,HttpServletResponse resp){
// System.out.println("testAjax");
String param = null;
param = req.getParameter("param");
// System.out.println(param);
Date date = new Date();
resp.setDateHeader("Last-Modified", date.getTime());
//为了更好地测试缓存效果,可以设置false:如xmlHttpRequest.open("GET", "./testAjax?param="+param, false);点击按钮就会卡住,知道几秒
//之后才可以
resp.setHeader("Pragma", "Pragma");
resp.setHeader("cache-control", "public");
int mills = 0;
while(mills < 5){
try {
Thread.sleep(1000);
System.out.println("睡眠"+mills+"秒后");
mills ++ ;
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
PrintWriter pw = null;
try {
pw = resp.getWriter();
pw.print(param);
} catch (IOException e) {
e.printStackTrace();
}finally{
pw.flush();
pw.close();
System.out.println("finally");
}
}
}