我们在弄网站的时候,特别是大流量的网站。经常会遇到首页速度比较慢的情况。很多时候就是因为首页运用了大量的数据库操作。遇到这种情况怎么办好呢?就单一的一个页面,如果套用一套摸板再生成首页似乎工作量似乎会不小。我的建议是采用直接抓取动态页面并生成静态页面。
JJAVA代码:com.function
package com.function;
import java.io.*; import java.net.*; /** * @author 大鱼 * * 抓取网站上的页面并生成一静态页面 */ public class function {
public String snatch(String web_url, String coding, String file) { //web_url:抓取页面的地址 //coding:抓取页面的编码 //生成后的文件名 (实际文件地址) String sCurrentLine=""; String return_msg=""; InputStream l_urlStream; FileWriter fw; try { String sTotalString=""; URL l_url = new URL(web_url); java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) l_url.openConnection(); l_connection.connect(); l_urlStream = l_connection.getInputStream(); java.io.InputStreamReader read = new InputStreamReader(l_urlStream,coding); java.io.BufferedReader l_reader = new java.io.BufferedReader(read);
while ((sCurrentLine = l_reader.readLine()) != null) { sTotalString += sCurrentLine; } sTotalString= this.contentchange(sTotalString); String path = file;
File fileName = new File(path); if (fileName.exists()) { // 删除File.txt档 // fileName.delete(); } else { // 在目前的目录下建立一个名为File.txt的文字档 fileName.createNewFile(); fileName.createNewFile(); }
fw = new FileWriter(path); // 将字串写入文件 fw.write(sTotalString); fw.close(); return_msg="操作完毕,页面已生成!"; return return_msg; } catch (MalformedURLException e) { // TODO Auto-generated catch block return "操作失败,页面未生成!"; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block return "操作失败,页面未生成!"; } catch (IOException e) { // TODO Auto-generated catch block return "操作失败,页面未生成!"; } } private String contentchange(String content) { //用于对页面的代码进行处理,例如对页面中的框架进行代码抽取并组合等 String str_return=content; return str_return; } }
页面调用代码:
<%@ page contentType="text/html;charset=gb2312" %> <%@ page language="java"%> <%@ page import="com.function.*"%> <% String path = request.getRealPath("/"); path=path+"index_n.html"; System.out.print(path); String web_url = http://www.wapsun.com; function fun = new function(); String msg = fun.snatch(web_url,"gb2312",path); System.out.print(msg); // %>
大鱼原创(Q:120673406)----转载请标明
|