本站首页    管理页面    写新日志    退出


天堂之光 人间希望

你我共同品味

JAVA的浓香.

Linux的清芬.

«August 2025»
12
3456789
10111213141516
17181920212223
24252627282930
31


我的分类(专题)

日志更新

最新评论

留言板

链接

联系我

msn:zhanglincon@hotmail.com


Blog信息
blog名称:
日志总数:99
评论数量:281
留言数量:4
访问次数:808642
建立时间:2005年11月17日




[Java与模式]jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

zhanglincon 发表于 2008/1/29 15:17:50

jsp生成静态页(jsp+servlet+xml)package ningxia.bl.admin.contentrele;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import java.sql.Connection;import java.sql.SQLException;import java.util.Calendar;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import ningxia.dao.admin.contentrele.ContentTreleMysql;import ningxia.dao.admin.newsclassmang.NewsClassMysql;import ningxia.dao.admin.newsmang.NewsMysql;import ningxia.utils.db.DBConnectionDAO;import ningxia.vo.admin.NewsBean;import ningxia.vo.admin.NewsClassBean;import ningxia.vo.admin.PageBean;import ningxia.vo.SessionABC;public class StaticPageServlet extends HttpServlet {private Connection conn;public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException{  doPost(request,response);}public void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException    {  PrintWriter out = response.getWriter();    HttpSession session = request.getSession();    //System.out.println("**********project start***********");    String id = request.getParameter("static");    //System.out.println("The id is "+id);    int pageno = new Integer(request.getParameter("pageno")).intValue();    boolean commitflg = false;    try    {            //System.out.println("*************ready data out*********");      //建立到数据库的链接      this.conn = DBConnectionDAO.getConnection();      conn.setAutoCommit(false);      //实例化ContentTreleMysql()类      ContentTreleMysql contenttrelemysql = new ContentTreleMysql(conn);      NewsClassMysql newsclassmysql = new NewsClassMysql(conn);            NewsBean news = new NewsBean();      news = contenttrelemysql.FindNew(id);      //System.out.println("**********The For Cycle is start*********");      /**      * 读取数据库存储的新闻记录      */      String newsid = news.getNews_id();      //System.out.println("---------The newsid is "+newsid+"-----------------");      String title = news.getNews_title();//读取新闻标题      String newssubtitle = news.getNews_subtitle();//读取新闻副标题      String newsauthor = news.getNews_author();//读取新闻作者姓名      String newsaddtime = news.getNews_addtime();//新闻添加时间      String newssource = news.getNews_source();//新闻采集地点      String newscontent = news.getNews_content();//新闻内容      String classid = news.getNews_classid();//新闻所属栏目ID      String newstemppath = news.getNews_newstemppath();//新闻模板路径      String newstempname = news.getNews_newstemplet();//读取新闻模文件名      String newsvideoflg = news.getNews_videoflg();      //System.out.println("The video flg is "+newsvideoflg);      int newslevel = news.getNews_level();//取得该新闻的栏目深度            //判断是否是视频新闻      String videourl = "";      String videodisplay = "";      if(newsvideoflg.equals("1")==true)      {        //该新闻是视频新闻        videodisplay = "block";        videourl = news.getNews_videosavepath()+news.getNews_videoname();        //System.out.println("The video url is "+videourl);      }      else      {        videodisplay = "none";        videourl = "";      }            //控制新闻标题的长度      String newstitle = "";      if(title.length()>=12)      {        newstitle = title.substring(0,11)+"......";      }      else      {        newstitle = title;      }                  //根据newslevel来判断生成的静态页引用样式的路径      String path = "";String pathurl = "";      for(int i = 1;i<=newslevel;i++)      {        path = path + "../";      }      pathurl = path+"../";            //根据newslevel来判断      String newsclassid = "";String pareid = "";      newsclassid = news.getNews_classid();      pareid = newsclassid.substring(0,3);      //System.out.println("The pareid is "+pareid);      String pareclasscname = newsclassmysql.FindNewsClassCnameByClassID(pareid);      //System.out.println("The classcnname is "+classcname);      String classcnname = newsclassmysql.FindNewsClassCnameByClassID(newsclassid);            //初始化NewsClassBean      NewsClassBean newsclass = new NewsClassBean();      newsclass = contenttrelemysql.FindClassId(classid);      //String newsclass_enname = newsclass.getNewsclass_enname();//查询栏目英文名称      String newsclass_savefilepath = newsclass.getNewsclass_savefilepath();//查询新闻栏目保存的路径      String filepath = request.getRealPath("/")+newstemppath+newstempname;            String templateC;      //调用时间函数      Calendar calendar = Calendar.getInstance();      String filename = String.valueOf(calendar.getTimeInMillis());      /**        * 下面的程序用来对静态页面生成并分页        * 判断新闻记录种的</p>数量来分页,每页30行字符         * 用allpagenum来判断页面大小        * 当pagenum取余数为0时则用整页显示        * 当pagenum取余数不为0时则用pagenum+1页显示        */            int line = 10 ;//每页显示10行      String arr[] = {};      //当分页标志即有</p>也有</br>时进行判断分页数      if(newscontent.split("</p>").length<=10&&newscontent.length()>=700&&newscontent.split("</br>").length>=10)      {        //用</br>来计算分页的页数        arr = newscontent.split("</br>");      }      else      if(newscontent.split("</br>").length<=10&&newscontent.length()>=700&&newscontent.split("</p>").length>=10)      {        //用</p>来计算分页的页数        arr = newscontent.split("</p>");      }      else      {        arr = newscontent.split("</p>");      }            //将数组内容按照</p>进行分割      int pagenum =arr.length/line;//需要多少页来显示数据      int length =arr.length;//数组长度      int other = arr.length%line;//最后一页所剩的行数      if(other!=0)      {        pagenum+=1;      }      /**        * 将静态页所在路径,静态页文件名称,静态页所属栏目ID存入数据库        */      String staticfilename = filename+"_0.htm";//首页文件名      String staticfilepath = newsclass_savefilepath;//首页路径      String lp = filename+"_"+(pagenum-1)+".htm";//末页文件名      news.setNews_staticpagepath(staticfilepath);      news.setNews_staticfilename(staticfilename);      news.setNews_staticpagenum(pagenum);      contenttrelemysql.AddStaticPage(news);      /**        * 开始生成静态页面        */      int q = 0;      String c;      String page ="";      int h = line;      for(int k=1;k<=pagenum;k++)      {        String a = "<a href="+filename+"_"+(k-1)+".htm>"+k+"</a>";        page =page+a;      }      for(int j=1;j<=pagenum;j++)      {        if((j==pagenum)&&(other!=0))        {        //最后一页        //取得剩余行数        for(int n=q;n<=length-1;n++)        {          //System.out.println("The Q is "+q);          //循环取出数据          content+=arr[n];        }        //替换模板页        FileInputStream fileinputstream = new FileInputStream(filepath);//读取模块文件                int lenght = fileinputstream.available();        byte bytes[] = new byte[lenght];                                                                      fileinputstream.read(bytes);                                                                          fileinputstream.close();                                                                    templateContent = new String(bytes);        templateContent = templateContent.replaceAll("###path###", path);        templateContent = templateContent.replaceAll("###pathurl###", pathurl);        templateContent = templateContent.replaceAll("###newsId###", newsid);        templateContent = templateContent.replaceAll("###pareclassid###", pareid);        templateContent = templateContent.replaceAll("###pareclasscnname###", pareclasscname);        templateContent = templateContent.replaceAll("###newsclassid###", newsclassid);        templateContent = templateContent.replaceAll("###classcnname###", classcnname);        templateContent = templateContent.replaceAll("###newstitle###", newstitle);        templateContent = templateContent.replaceAll("###newssubtitle###", newssubtitle);        templateContent = templateContent.replaceAll("###newsauthor###", newsauthor);        templateContent = templateContent.replaceAll("###newsaddtime###", newsaddtime);        templateContent = templateContent.replaceAll("###newssource###", newssource);        templateContent = templateContent.replaceAll("###videodisplay###", videodisplay);        templateContent = templateContent.replaceAll("###videourl###", videourl);        templateContent = templateContent.replaceAll("###newscontent###", content);        templateContent = templateContent.replaceAll("###first###", staticfilename);        templateContent = templateContent.replaceAll("###number###", page);        templateContent = templateContent.replaceAll("###last###", lp);        String fileame_m = filename +"_"+(j-1)+".htm";        //System.out.println("The fileame is "+fileame);        String file = request.getRealPath("/")+newsclass_savefilepath+"/"+fileame_m;//生成html文件并存储绝对路径        //System.out.println("The file is "+file);        FileOutputStream fileoutputstream = new FileOutputStream(file);//建立文件输出流        byte tag_bytes[] = templateContent.getBytes();          fileoutputstream.write(tag_bytes);         fileoutputstream.close();        //System.out.println("This is the ++++"+j+"++++"+content);        }        else        {                //System.out.println("h is "+h);        for(int m=q;;)        {          content+=arr[m];          m++;          q=m;                    if(q>=h)          {            //替换模板页            FileInputStream fileinputstream = new FileInputStream(filepath);//读取模块文件                        int lenght = fileinputstream.available();            byte bytes[] = new byte[lenght];                                                                          fileinputstream.read(bytes);                                                                              fileinputstream.close();                                                                        templateContent = new String(bytes);                templateContent = templateContent.replaceAll("###path###", path);            templateContent = templateContent.replaceAll("###pathurl###", pathurl);            templateContent = templateContent.replaceAll("###newsId###", newsid);            templateContent = templateContent.replaceAll("###pareclassid###", pareid);            templateContent = templateContent.replaceAll("###pareclasscnname###", pareclasscname);            templateContent = templateContent.replaceAll("###newsclassid###", newsclassid);            templateContent = templateContent.replaceAll("###classcnname###", classcnname);            templateContent = templateContent.replaceAll("###newstitle###", newstitle);            templateContent = templateContent.replaceAll("###newssubtitle###", newssubtitle);            templateContent = templateContent.replaceAll("###newsauthor###", newsauthor);            templateContent = templateContent.replaceAll("###newsaddtime###", newsaddtime);            templateContent = templateContent.replaceAll("###newssource###", newssource);            templateContent = templateContent.replaceAll("###videodisplay###", videodisplay);            templateContent = templateContent.replaceAll("###videourl###", videourl);            templateContent = templateContent.replaceAll("###newscontent###", content);            templateContent = templateContent.replaceAll("###first###", staticfilename);            templateContent = templateContent.replaceAll("###number###", page);            templateContent = templateContent.replaceAll("###last###", lp);            String fileame_m = filename +"_"+(j-1)+".htm";            String file = request.getRealPath("/")+newsclass_savefilepath+"/"+fileame_m;//生成html文件并存储绝对路径            FileOutputStream fileoutputstream = new FileOutputStream(file);//建立文件输出流            byte tag_bytes[] = templateContent.getBytes();              fileoutputstream.write(tag_bytes);             fileoutputstream.close();            c;            h=line+h;            break;          }                    }        }      }      NewsMysql newsmysql = new NewsMysql(conn);      PageBean pagebean = new PageBean();    pagebean = newsmysql.FindNewsByPage(pageno, classid);      conn.commit();      session.setAttribute(SessionABC.NEWSPAGEINFO, pagebean);      response.sendRedirect("admin/admin_newsmang.jsp");    }    catch (Exception e)    {      out.print(e.getMessage());    }    finally    {      if (conn != null)   {    try {    if (commitflg)      conn.rollback();      conn.close();        }         catch (SQLException sqe)         {        sqe.printStackTrace();        session.setAttribute("SessionABC.ERRORMSG", "数据库连接关闭时发生错误");        response.sendRedirect("admin/error.jsp");        }  }    }    }}在xml中添加StaticPageServlet.do就可以了!试试吧生成静态文件的代码.其实我还是比较赞成使用freemarker生成静态页或是使用服务器端读取jsp页来生成静态页。package com.ntsky.cms.template;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Iterator;import java.util.Map;import java.util.Set;import org.apache.log4j.Logger;import freemarker.template.Configuration;import freemarker.template.DefaultObjectWrapper;import freemarker.template.Template;import freemarker.template.TemplateException;import com.ntsky.framework.util.FileUtil;import com.ntsky.framework.util.StringUtil;import com.ntsky.cms.exception.BuildHtmlException;/*** 模板工具类* @author Administrator**/public class TemplateManager {        public static Logger logger = Logger.getLogger(TemplateManager.class.getName());    private static TemplateManager templateManager = null;    private Configuration configuration = null;        public TemplateManager(){        // 设置freemarker的参数        configuration = new Configuration();        // setDirectoryForTemplateLoading("/template");        configuration.setObjectWrapper(new DefaultObjectWrapper());        configuration.setDefaultEncoding("UTF-8");    }    /**    * 取得模板处理的实例    * @return templateManager 模板处理实例    */    public synchronized static TemplateManager getInstance(){        if( templateManager == null ){            templateManager = new TemplateManager();        }        return templateManager;    }    /**    * 生成静态文件<br/>    * [概要]<br/>    *        <p>读取模板文件生成静态文件</p>    *     * [详细]<br/>    * <ol>    *    <li>取得模板文件</li>    *    <li>设置生成文件路径</li>    *    <li>载入objectMap中的内容生成文件</li>    * </ol>    *     * @param templateFolder 模板相对于classpath的路径    * @param templateFileName 模版名称    * @param htmlFolder 要生成的静态文件的目录     * @param htmlFileName 要生成的文件名    * @param objectMap 模板中对象集合     * @return boolean 是否生成成功    */    public void buildFile(String templateFolder,String templateFileName,String htmlFolder,String htmlFileName,Map objectMap) throws BuildHtmlException{        this.buildFile(templateFolder,templateFileName,StringUtil.applyRelativePath(htmlFolder,htmlFileName),objectMap);    }    /**    * 生成静态文件<br/>    * [概要]<br/>    *        <p>读取模板文件生成静态文件</p>    *     * [详细]<br/>    * <ol>    *    <li>取得模板文件</li>    *    <li>设置生成文件路径</li>    *    <li>载入objectMap中的内容生成文件</li>    * </ol>    *     * @param templateFolder 模板相对于classpath的路径    * @param templateFileName 模版名称    * @param htmlFilePath 要生成的静态文件的路径    * @param objectMap 模板中对象集合     * @return boolean 是否生成成功    */    public void buildFile(String templateFolder,String templateFileName,String htmlFilePath,Map objectMap) throws BuildHtmlException{        Writer out = null;        try {            //configuration.setClassForTemplateLoading(this.getClass(), templateFolder);            configuration.setDirectoryForTemplateLoading(new File(templateFolder));            Template template = configuration.getTemplate(templateFileName);            template.setEncoding("UTF-8");            //创建生成文件目录            File htmlFile = new File(htmlFilePath);            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"UTF-8"));            template.process(objectMap,out);            out.flush();        } catch (TemplateException ex){            logger.error("Build Error"+templateFileName,ex);            throw new BuildHtmlException(ex.getMessage());        } catch (IOException e) {            logger.error("Build Error"+templateFileName,e);            throw new BuildHtmlException(e.getMessage());        }        finally{            try {                out.close();            } catch (IOException e) {                logger.error(e.getMessage(),e);            }        }    }        /**    * 生成多个文件    *     * @param templateFolder 模板目录    * @param templateMap 模板和文件对应的映射    * @param objectMap 对象Map    */    public void buildFiles(String templateFolder, Map templateMap, Map objectMap){        Set set = templateMap.entrySet();        Iterator iterator = set.iterator();        Map.Entry entry = null;        String templateFileName = null;        String filePath = null;        while (iterator.hasNext()) {            entry = (Map.Entry) iterator.next();            templateFileName = (String)entry.getKey();            filePath = (String)entry.getValue();            this.buildFile(templateFolder,templateFileName,filePath,objectMap);        }    } }


阅读全文(6541) | 回复(9) | 编辑 | 精华
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

yongcf(游客)发表评论于2008/11/30 14:12:52

前辈,你好,我是大四的学生,我毕业设计要求做一个新闻发布系统,我也想采用生成静态页技术,能给点资料吗?谢谢了。 邮箱:yongcf@sina.com


个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

都市大连网(游客)发表评论于2008/11/19 17:15:02

给一份源代码谢谢 eyonet@qq.com  

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

king(游客)发表评论于2008/9/10 14:04:01

能不能发下源代码。谢谢了majun4678@163.com

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

zookie(游客)发表评论于2008/8/4 8:14:24

楼主,能不能把这个程序完整的代码发给我啊,weokme@163.com 谢谢啦 QQ:526881969

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

kuangfeng(游客)发表评论于2008/7/25 16:55:32

楼主能不能把你的代码给我一份啊,不胜感激!kuangfeng88588@163.com

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

jlovej(游客)发表评论于2008/5/8 11:13:18

楼主能不能把这个程序的完整代码发给我啊,我将感激不尽,因为我也正研究这个呢,只是不知道怎么下手!E-mail:rongdajian@126.com

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

Kinogam发表评论于2008/1/31 9:05:29

不过生成静态页的话可以用xslt转换XML

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

zhanglincon发表评论于2008/1/30 14:38:04

以下引用kinogam在2008-1-30 11:36:25的评论:每次看到JAVA开发引入一大堆包都觉得很不可思议…… 如果仅仅这样会导致你的文件太大import java.io.*;import javax.servlet.http.*;

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


回复:jsp生成静态页(jsp+servlet+xml)
文章收藏,  软件技术

Kinogam发表评论于2008/1/30 11:36:25

每次看到JAVA开发引入一大堆包都觉得很不可思议……

个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


» 1 »

发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.063 second(s), page refreshed 144778945 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号