Java freemarker demo 【struts + freemarker】 自己修改的一个小例子

来源:互联网 发布:淘宝助理菜鸟组件 编辑:程序博客网 时间:2024/06/06 01:05

废话不多说,直接拿去用吧,至于freemarker有哪些标签怎么使用,百度一大堆,把项目运行起来自己建个测试数据,慢慢调试吧!

项目下载路径:http://download.csdn.net/detail/lovelong8808/8426379

项目结构:


action:

package com.lwl.action;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import org.apache.log4j.Logger;import org.apache.struts2.ServletActionContext;import com.lwl.model.User;import com.lwl.util.FreeMarkerUtil;import com.opensymphony.xwork2.ActionSupport;public class ReleaseNewsAction extends ActionSupport {private static final long serialVersionUID = 1L;private static final Logger logger = Logger.getLogger(ReleaseNewsAction.class);private User user;//测试用的model对象 没有具体意义  后期可以自己自定义private String msg;/** * 主要处理文件生成的 action *  * 此方法一般是后台操作,让某个页面生成静态文件, *  所有后期的话 建议将此方法修改为json请求,判断是否生成功 * @return * @throws Exception */@SuppressWarnings("rawtypes")public String doRelease() throws Exception {logger.info("Prepare releasing news...");//获取 前台数据 添加到model类里面//创建map集合  将结果集 添加到map中Map  root = new HashMap();//root.put("user", user);//填充数据root = getData(root, user);//获取请求对象HttpServletRequest request = ServletActionContext.getRequest();//生成的文件名称//防止浏览器缓存,用于重新生成新的html  UUID uuid = UUID.randomUUID();  String htmlFileName = uuid+user.getNewsId() + ".html";//获取请求真实路径String rootPath = request.getSession().getServletContext().getRealPath("/");//如果文件已经存在  则不操作 [可以防止后台用户重复操作]if(!FreeMarkerUtil.isexistHtml(rootPath, htmlFileName)){//生成文件boolean flag = FreeMarkerUtil.genHtmlFile(rootPath,"/news.ftl", root, FreeMarkerUtil.filePath, htmlFileName);//判断是否成成功if (flag == true) {//如果生成成功 则将生成的路径 填写到对象的url中user.setUrl(request.getContextPath() + FreeMarkerUtil.filePath + htmlFileName);user.setFilename(htmlFileName);logger.info("生成文件:" + FreeMarkerUtil.filePath + htmlFileName + "成功!");} else {return ERROR;}}else{//什么事也不干}request.setAttribute("user", user);return SUCCESS;}/** * 刷新页面 * @return */@SuppressWarnings("rawtypes")public String refresh(){Map  root = new HashMap();//填充数据root = getData(root, user);//获取请求对象HttpServletRequest request = ServletActionContext.getRequest();//生成的文件名称UUID uuid = UUID.randomUUID();  String htmlFileName = uuid+user.getNewsId() + ".html";//获取请求真实路径String rootPath = request.getSession().getServletContext().getRealPath("/");//删除之前的文件 FreeMarkerUtil.delOldHtml(rootPath, user.getFilename());//刷新一下静态文件boolean flag = FreeMarkerUtil.genHtmlFile(rootPath,"/news.ftl", root, FreeMarkerUtil.filePath, htmlFileName);//判断是否成成功if (flag == true) {//如果生成成功 则将生成的路径 填写到对象的url中user.setUrl(request.getContextPath() + FreeMarkerUtil.filePath + htmlFileName);user.setFilename(htmlFileName);logger.info("生成文件:" + FreeMarkerUtil.filePath + htmlFileName + "成功!");} else {return ERROR;}msg = "O(∩_∩)O哈哈~,逗比你刷成功了!";return SUCCESS;} public String hello(){msg = "O(∩_∩)O哈哈~,欢迎逗比";return SUCCESS;}/** * 用于存储数据  模仿用 * @param root * @param user * @return */@SuppressWarnings({ "rawtypes", "unchecked" })public Map getData(Map root,User user){//添加对象root.put("user", user);//添加集合List<User> list = new ArrayList<User>();for(int i=0;i<5;i++){list.add(user);}root.put("userlist", list);return root;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}

freemarker 的工具类

package com.lwl.util;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.Map;import javax.servlet.ServletContext;import org.apache.log4j.Logger;import org.apache.struts2.ServletActionContext;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;/** * 模板的工具类 * @author lwl * */public class FreeMarkerUtil {private static final Logger logger = Logger.getLogger(FreeMarkerUtil.class);private static final String encoding = "UTF-8";private static Configuration configuration;public static String filePath="/news/";//文件存放路径/** * 读取所有模板配置信息 * @return */public static Configuration getConfiguration() {if (null == configuration) {configuration = new Configuration();}configuration.setDefaultEncoding(encoding);ServletContext context = ServletActionContext.getServletContext();logger.info("Set servletContext for template loading at WEB-INF/freemarker");configuration.setServletContextForTemplateLoading(context, "WEB-INF/template/");return configuration;}/** *  * @param rootPath  项目在服务器路径 * @param templateFileName  freemarker模板名称 * @param rootMap 数据模型 * @param htmlFilePath  生成文件所在位置 * @param htmlFileName  生成文件的名称 * @return */public static boolean genHtmlFile(String rootPath, String templateFileName,Map<?, ?> rootMap, String htmlFilePath, String htmlFileName) {try {//获取对应的freemarker模板Template t = getConfiguration().getTemplate(templateFileName);//设置字符集t.setEncoding(encoding);logger.info("创建文件:" + rootPath + "/" + htmlFilePath + "/"+ htmlFileName);//创建文件对象File file = new File(rootPath + "/" + htmlFilePath + "/"+ htmlFileName);//写出对象Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));t.setOutputEncoding(encoding);t.process(rootMap, bw);bw.flush();bw.close();} catch (TemplateException te) {logger.error("读取FreeMarker文件模板出错:" + te.toString());return false;} catch (IOException ioe) { ioe.printStackTrace();logger.error("I/O出错:" + ioe.toString());return false;}return true;}/** * 判断文件是否已经存在 * @param rootPath 项目在服务器路径 * @param name 文件名称 * @return */public static  boolean isexistHtml(String rootPath,String name){File file = new File(rootPath + filePath);//判断服务器是否有次文件夹if (file.isDirectory()) {logger.info("存放html文件的文件夹目录是:" + file.getAbsolutePath());} else {logger.info(rootPath + filePath + "不是可用目录");file.mkdirs();}  /**         * 判断是否已经存在该html文件,存在了就直接访问html ,不存在生成html文件         */         String[] indexfileList = file.list(new DirectoryFilter(name));         if(indexfileList==null){        logger.info(rootPath + filePath + "文件不存在");        return false;        }        if(indexfileList.length<=0){         logger.info(rootPath + filePath + "文件不存在");        return false;        }else{         logger.info(rootPath + filePath + "文件已经存在");        return true;        }  }/**      * 删除原来的html文件      * @param htmlDir      * @param htmlName      */      public static boolean delOldHtml(String htmlDir,String name){           File path = new File(htmlDir);           String[] indexfileList = path.list(new DirectoryFilter(name));          if(indexfileList==null){         return false;         }         if(indexfileList.length>=0){               for(String f:indexfileList){                   File delf = new File(htmlDir+"/"+f);                   delf.delete();              }          }          return true;    }  }

文件判断的工具类:

package com.lwl.util;import java.io.File;import java.io.FilenameFilter;/** * 判断文件名是否存在 * @author FORENMS * */public class DirectoryFilter implements FilenameFilter {private String str;public DirectoryFilter(String str){this.str = str;}public boolean accept(File dir, String name) {        String f= new File(name).getName();           if(f.contains(str) || f.equals(str)){             return true;          }          return false; }}

项目实体类:

package com.lwl.model;public class User {private String newsId;private String title;private String author;private String content;private String url;private String filename;public String getNewsId() {return newsId;}public void setNewsId(String newsId) {this.newsId = newsId;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getFilename() {return filename;}public void setFilename(String filename) {this.filename = filename;}}

struts的配置文件

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "struts-2.1.dtd" ><struts><package name="lwl" extends="struts-default"><action name="doRelease" class="com.lwl.action.ReleaseNewsAction"method="doRelease"><result name="success">/success.jsp</result><result name="error">/error.jsp</result></action><action name="hello" class="com.lwl.action.ReleaseNewsAction"method="hello"><result name="success">/WEB-INF/hello.jsp</result></action><action name="refresh" class="com.lwl.action.ReleaseNewsAction"method="refresh"><result name="success">/WEB-INF/hello.jsp</result><result name="error">/error.jsp</result></action></package></struts>

web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>

freemarker的模板页面 news.ftl

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>${user.title}</title></head><body><div><a href="/Freemarker/">回到首页</a><br/><a href="/Freemarker/hello.action">回到欢迎界面</a><!--取出一个对象--><br/>以下获取对象数据:<br/>新闻标题:${user.title}<br/>新闻作者:${user.author}<br/>新闻内容:${user.content}<br/><!--取出一个对象--><!--循环集合-->以下循环集合数据:<br/><#list userlist as us>第${us_index+1}个用户  新闻标题:${us.title}  新闻作者:${us.author}  新闻内容: ${us.content}<hr/>  </#list><!--循环集合--></div></html>

首页页面:index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page">  </head>  <body><form action="${pageContext.request.contextPath}/doRelease.action" method="post">编号:<input type="text" name="user.newsId"><br/>标题:<input type="text" name="user.title" /><br/>作者:<input type="text" name="user.author" /><br/>正文:<textarea rows="5" cols="30" name="user.content"></textarea><br/><input type="submit" value="submit"/></form>  </body></html>

表单提交成功页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP 'success.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>  release successfully! <a href="${user.url}">${user.url}</a>${user.newsId}<hr/>${user.title}<hr/>${user.author}<hr/>${user.content}  </body></html>

表单提交失败页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP 'error.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page">  </head>    <body>error  </body></html>

静态页面生成页面里面用于测试跳转页面:hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>${msg}</body></html>




0 0