最近在学习freemarker,这个模板技术已经很成熟,文档也很多。我研究了下利用它来实现页面静态化,静态化的好处你懂的,好了贴一下主要的代码。
首先是web.xml。
<servlet>
<servlet-name>springMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springMVCservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath*:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
然后是springMVC-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:property-placeholder location="/WEB-INF/classes/*.properties" />
<context:component-scan base-package="com.qingshuang.circ"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/images/**" location="http://location:8888/images/" />
<mvc:resources mapping="/css/**" location="http://location:8888/css/" />
<mvc:resources mapping="/js/**" location="http://location:8888/js/" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="false" />
<property name="suffix" value="" />
<property name="contentType" value="text/html;charset=UTF-8">property>
<property name="requestContextAttribute" value="request" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
bean>
<bean id="FreeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0prop>
<prop key="default_encoding">UTF-8prop>
<prop key="number_format">0.##########prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ssprop>
<prop key="classic_compatible">trueprop>
<prop key="template_exception_handler">ignoreprop>
props>
property>
bean>
beans>
接下来是fremarker工具类
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import freemarker.template.SimpleHash;
import freemarker.template.Template;
@Component
public class TemplateUtils {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Value("${sys.charset}")
private String charset;
/**日志类*/
public Log logger = LogFactory.getLog(this.getClass());
@SuppressWarnings("unchecked")
public String parse(String templateName, Object model) {
StringWriter out = null;
try {
Template template = freeMarkerConfigurer.getConfiguration()
.getTemplate(templateName, charset);
SimpleHash root = null;
if (model instanceof Map) {
root = new SimpleHash((Map, ?>) model);
} else {
root = new SimpleHash(BeanUtils.describe(model));
}
out = new StringWriter();
template.process(root, out);
} catch (Throwable e) {
logger.info("template error<"+templateName+">");
}
return out.toString();
}
public boolean createHtml(String str,String filePath,boolean flag){
boolean b = false;
File writeFile = new File(filePath);
try {
if (writeFile.exists()) {
if(flag){
writeFile.delete();
writeFile.createNewFile();
}else{
writeFile.createNewFile();
}
} else {
writeFile.delete();
writeFile.createNewFile();
}
OutputStream os=new FileOutputStream(writeFile, true);
os.write(str.getBytes("utf-8"));
os.close();
} catch (IOException e) {
logger.warn("create html error:"+filePath);
}
return b;
}
public FreeMarkerConfigurer getFreeMarkerConfigurer() {
return freeMarkerConfigurer;
}
public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
this.freeMarkerConfigurer = freeMarkerConfigurer;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
}
然后是控制器调用代码
@Controller
public class FreeMarkerController extends BaseController{
@Autowired
private FreeMarkerConfigurer config;
@Autowired
private TemplateUtils templateUtils;
@RequestMapping(value="/freemarker/freemarkerTest", method=RequestMethod.GET)
public ModelAndView Add(HttpServletRequest request, HttpServletResponse response) {
System.out.println("Test... ...");
User user = new User();
user.setUsername("张小凡");
user.setPassword("1234");
User user1 = new User();
user1.setUsername("陆雪琪");
user1.setPassword("5678");
List users = new ArrayList();
users.add(user);
users.add(user1);
Map map = new HashMap();
map.put("users", users);
templateUtils.createHtml(templateUtils.parse("template/ftl/index.html", map), "D:\\temp\\"+user1.getPassword()+".html", true);
return new ModelAndView("template/ftl/index.html", "users", users);
}
public FreeMarkerConfigurer getConfig() {
return config;
}
public void setConfig(FreeMarkerConfigurer config) {
this.config = config;
}
public TemplateUtils getTemplateUtils() {
return templateUtils;
}
public void setTemplateUtils(TemplateUtils templateUtils) {
this.templateUtils = templateUtils;
}
}
html模板代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<#list users as user>
username : ${user.username}<br/>
password : ${user.password}
#list>
body>
html>
好了,有几个地方需要说明一下,首先是controller的方法,这里:
Map<String, Object> map = new HashMap<String, Object>();
map.put("users", users); templateUtils.createHtml(templateUtils.parse("template/ftl/index.html", map), "D:\\temp\\"+user1.getPassword()+".html", true);
return new ModelAndView("template/ftl/index.html", "users", users);
这里的意思是如果你不想生成html,只想页面显示数据,那么调用模板工具类这一行去掉就可以了。因为生成的html以id命名,那么你可以加上一个判断静态是否存在的逻辑,如果没有就生成否则直接跳转到静态页面,非常方便,如果想更新静态页面删除已经生成的页面即可,这样的好处就是非常灵活,然后配合后台的html编辑器就可以实现一个简单的cms。好了,先写到这里,有什么问题可以给我发邮件,一般晚上在。emai address:[email protected]