一、用波总提供的方法,简洁
// String file="store.html";
// Template template = RenderManager.me().getEngine().getTemplate("/WEB-INF/qt/"+file);
// Map<String,Object> map=new HashMap<>();
// map.put("size", page.getTotalPage());
// map.put("list", page.getList());
// map.put("index", 1);
// template.render(map,file);//直接输出,简洁但是有一个问题,就是如果要更新全部静态页面,就得设置每一个map值。
二、为了解决上面问题,我使用jsoup
<!-- json操作 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
1、Util1类
//获取sqt的全路径,用于读取它下面的文件
public static String sqtPath=PathKit.getWebRootPath()+"/WEB-INF/sqt/";
/**
* 查看文件是否存在
* path 全路径
* true存在
*/
public boolean isFile(String path) {
System.out.println("判断文件是否存在-文件路径:"+path);
File file=new File(path);
return file.exists();
}
/**
* 通过URL得到document,谷歌浏览器
*/
public Document getDocument(String url){
//获取请求链接
Connection conn=Jsoup.connect(url).timeout(5000);
//请求头设置
conn.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.header("Accept-Encoding", "gzip, deflate, sdch");
conn.header("Accept-Language", "zh-CN,zh;q=0.8");
conn.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
try {
return conn.get();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 通过URL,获取该页面源码
*/
public String getHtml(String url){
Document doc=getDocument(url);//获取document对象
return doc.html();
}
/**
* 生成静态页面-解决高并发
*/
public void staticPage(String filePath, String content) {
Path path = Paths.get(sqtPath+filePath);
//使用newBufferedWriter创建文件并写文件,会覆盖
//使用try-with-resource方法关闭流,不用手动关闭
try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
bw.write(content);
}catch (Exception e) {
e.printStackTrace();
}
}
2、controller类
/**
* 生成静态页面
*/
//爬取所有页面
public void staticPage() {
String content=util1.getHtml("http://localhost:8089/store");
util1.staticPage("store.html", content);
}
对应页面访问方法
//门店
public void store() {
boolean b=util1.isFile(util1.sqtPath+"store.html");//判断文件是否存在
if(b) {
System.out.println("静态页面输出:store.html");
render("/WEB-INF/sqt/"+"store.html");
}else {
Page<Store> page=is.getStorePage(1, 9);
setAttr("size",page.getTotalPage());
setAttr("list",page.getList());
setAttr("index",1);
render("store.html");
}
} 大功告成。