FreeMarker生成静态HTML页面的工具类FreeMarkerUtil

FreeMarker生成静态HTML页面的工具类FreeMarkerUtil

 

一.FreeMarkerUtil工具类:

import com.huaxia.entity.News;
import com.huaxia.entity.User;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 创建人: leon
 * 创建时间: 2014年11月28日 上午10:07:51
 * 类描述:Freemarker的工具类
 */
public class FreemarkerUtil {

	/**
	 * 通过指定的名字获取相应的模板
	 * @param fileName
	 * @return
	 */
	public Template getTemplate(HttpServletRequest request,String fileName) {
		try {
		Configuration cfg = new Configuration();
		cfg.setOutputEncoding("UTF-8");
        cfg.setDefaultEncoding("UTF-8");// 编码设置1  
        cfg.setEncoding(Locale.CHINA, "UTF-8");
		//设定读取ftl模板文件的目录
		//cfg.setClassForTemplateLoading(this.getClass(), "/template");		//读取src目录下
		cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");	//读取webroot目录下
		//在模板文件目录中找到名称为name的文件,并加载为模板
		Template template = cfg.getTemplate(fileName);
		template.setEncoding("UTF-8");// 编码设置2
		return template;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 通过指定的文件目录和文件名生成相应的文件
	 * @param fileDir
	 * @param fileName
	 */
	public Boolean printToFile(Template template,String fileDir,String fileName,Map<String,Object> root) {
		boolean done = false;
		Writer writer = null;
		try {
			//判断多级目录是否存在,不存在则一级级创建
			String[] paths = fileDir.split("\\\\");//注意:此处“\\”是错误的,必须要“\\\\”才能分割字符串
			String dir = paths[0];
			for (int i = 1; i < paths.length; i++) {
				dir = dir + File.separator + paths[i];
				File file=new File(dir.toString());
				if (!file.exists()) {
					file.mkdir();
				}
			}
			//创建输出流
			File file = new File(fileDir +File.separator+ fileName);  
			   
	        //设置生成的文件编码为UTF-8   
	        //服务器不支持UTF-8格式HTML时候使用ANSI格式HTML文件,即系统默认编码   
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));  // 编码设置3
			//writer = new FileWriter(fileDir +File.separator+ fileName);
			//输出模板和数据模型都对应的文件
			template.process(root, writer);
			done = true;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
	        e.printStackTrace();
	    } finally {
			try {
				if(writer!=null){
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
		return done;
	}
	
	/**
	 * 通过传入的请求和新闻信息重新生成html文件
	 * @param news  //新闻实体类
	 * @param request   //请求
	 * @param user  //用户
	 * @return
	 */
	public boolean genenateHtml(News news,HttpServletRequest request,User user) {
		String fileName = news.getFileName();
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("id", news.getId());
		root.put("title", news.getTitle());
		root.put("create_date", news.getCreateDate());
		root.put("creator", news.getCreator());
        root.put("content", ClobUtil.ClobToString(news.getContent()));
        root.put("fileName", news.getUploadFile()==null?"":news.getUploadFile());
		FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
		Template template = null;
        template = freemarkerUtil.getTemplate(request, "news.ftl");//新闻发布系统的freemarker模板
		String htmlDir = news.getDir();
		boolean done = printToFile(template, htmlDir, fileName, root);
		return done;
	}
}

 

二.发布新闻信息的Servlet:

if ("publishNews".equals(action)) {     //发布新闻:通过传入的新闻id获取新闻信息生成新闻模板
    String idsStr = request.getParameter("newsIds");
    INewsDao newsDao = new NewsDaoImpl();
    boolean done = newsDao.publishNews(idsStr,request,user);
    String str =null;
    if(done){
        str="{success:true}";
    }else{
        str="{success:false}";
    }
    response.setContentType("text/html;charset=UTF-8");
    out=response.getWriter();
    out.print(str);     
    out.close();
    return;
}

 

三.发布新闻信息的Dao方法:

/**
 * 发布新闻信息的Dao方法
 * @param idsStr    //新闻ID
 * @param request
 * @param user
 */
public boolean publishNews(String idsStr, HttpServletRequest request, User user) {
    Session s = null;
    boolean done = false;
    FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
    List<Integer> ids = new ArrayList<Integer>();
    String[] newIds = idsStr.split(",");
    for (int i = 0; i < newIds.length; i++) {
        ids.add(Integer.valueOf(newIds[i]));
    }
    try {
        s = HibernateUtil.getSession();
        s.beginTransaction();
        StringBuffer sb = new StringBuffer("select * from news where id in(");
        for (int i = 0; i < ids.size(); i++) {
            sb.append(ids.get(i));
            if (i != ids.size() -1) {
                sb.append(",");
            }
        }
        sb.append(")");
        SQLQuery query = s.createSQLQuery(sb.toString());
        List<News> list = query.addEntity(News.class).list();
        for (int i = 0; i < list.size(); i++) {
            News news = list.get(i);
            done = freemarkerUtil.genenateHtml(news, request, user);
            if (!done) {
                return done;
            }
        }
        s.getTransaction().commit();
        done = true;
    } catch (Throwable e) {
        logger.error(e.toString());
        HibernateUtil.endSession(s);
    } finally {
        HibernateUtil.endSession(s);
    }
    return done;
}

 

 

相关链接:
Freemarker模板应用
Freemarker生成html页面
Freemarker 设置编码

 

 

 

 

你可能感兴趣的:(freemarker,新闻发布系统)