现在的位置: 首页 > 综合 > 正文

jsp生成静态新闻页面(一)也谈用JSP实现新郎、sohu新闻系统的技术。

2013年08月22日 ⁄ 综合 ⁄ 共 2159字 ⁄ 字号 评论关闭

(这个和把jsp生成静态html不同,这个所有的新闻都是静态的

使用了htm模板,不一样的地方就替换掉了

)

1、首先要一个写好的htm文件模板,然后几个需要替换的地方如新闻标题、新闻内容直接根据输入的来替换,文件名字就用日期如2000-12-18-1.htm类似的;

<%@ page language="java" contentType="text/html;charset=utf-8" errorPage=""%>
<%@ page import="java.util.*,java.io.*"%>
<%@ include file="../inc/includeBean.jsp"%>
<%
  request.setCharacterEncoding("utf-8");
  String title=request.getParameter("newstitle");
  String newsfrom = request.getParameter("newsfrom");
  String doct = request.getParameter("newsdoct");
  String fileame="";
  int a = 0;
  try{
    String filePath = "",path="";
    filePath = request.getRealPath("/")+"news/modle.html";
    filePath = filePath.replaceAll("////","/");
    String templateContent="";
 
    //读取hmtl模板文件
    FileInputStream fis = new FileInputStream(filePath);
    StringBuffer content = new StringBuffer();
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String line = null;
    while ((line = br.readLine()) != null)
    content.append(line + "/n");
    br.close();
    in.close();
    fis.close();
 
    //替换模板里面的相关部分
    templateContent = new String(content);
    templateContent=templateContent.replaceAll("###title###",title);
    templateContent=templateContent.replaceAll("###source###",newsfrom);
    templateContent=templateContent.replaceAll("###addtime###",nowTime);
    templateContent=templateContent.replaceAll("###article###",doct);//替换掉模块中相应的地方
    Calendar calendar = Calendar.getInstance();
    fileame = String.valueOf(calendar.getTimeInMillis()) +".html";
 
    //建立新闻页面存放目录
    path= request.getRealPath("/")+"news/"+nowTime+"/";
    File d=new File(path);//建立代表Sub目录的File对象,并得到它的一个引用
    if(!d.exists()){//检查Sub目录是否存在
       d.mkdir();//建立Sub目录
     }
    File f=new File(path,fileame);
    if(!f.exists()){//检查File.txt是否存在
       f.createNewFile();//在当前目录下建立一个名为File.txt的文件
    }
    fileame = request.getRealPath("/")+"news/"+nowTime+"/"+fileame;//生成的html文件保存路径
   
    //替换后的内容写入到文件
    FileOutputStream fos = new FileOutputStream(fileame);
    Writer output = new OutputStreamWriter(fos, "UTF-8");
    output.write(templateContent);
    output.close();
    fos.close();
 
  }catch(Exception e){
    System.out.print(e.toString());
  }
%>

2、数据库中同时保存文件标题、文件名、日期等信息,新闻内容等其他的信息就没有必要保留了;
3、前台调用直接从数据库中取XXX.htm文件名、文件标题就行了;

抱歉!评论已关闭.