Spring+Freemarker实现自定义方法

配置文件test.properties中添加Freemarker相关配置信息

locale=zh_TW  
url_escaping_charset=UTF-8  
message.cache_seconds=3600  
message.common_path=/WEB-INF/language/message 

#------------ Template ------------
template.encoding=UTF-8
template.update_delay=3600
template.number_format=0.######
template.boolean_format=true,false
template.datetime_format=yyyy-MM-dd
template.date_format=yyyy-MM-dd
template.time_format=HH:mm:ss
template.loader_path=/WEB-INF/template,classpath:/
template.suffix=.ftl

在spring中进行freemarker相关配置

<!-- freemarker配置 -->
    <bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPaths" value="${template.loader_path}" />
        <property name="freemarkerSettings">
            <props>
                <prop key="defaultEncoding">${template.encoding}</prop>
                <prop key="url_escaping_charset">${url_escaping_charset}</prop>
                <prop key="locale">${locale}</prop>
                <prop key="template_update_delay">${template.update_delay}</prop>
                <prop key="tag_syntax">auto_detect</prop>
                <prop key="whitespace_stripping">true</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="number_format">${template.number_format}</prop>
                <prop key="boolean_format">${template.boolean_format}</prop>
                <prop key="datetime_format">${template.datetime_format}</prop>
                <prop key="date_format">${template.date_format}</prop>
                <prop key="time_format">${template.time_format}</prop>
                <prop key="object_wrapper">freemarker.ext.beans.BeansWrapper</prop>
            </props>
        </property>
        <property name="freemarkerVariables">
            <map>
                <entry key="message" value-ref="messageMethod" />
            </map>
        </property>
    </bean>

模板实现国际化的方法,具体SpringUtils任何实现国际化在http://blog.csdn.net/snowcity1231/article/details/44152099

@Component("messageMethod")
public class MessageMethod implements TemplateMethodModel {

    @SuppressWarnings("rawtypes")
    public Object exec(List arguments) throws TemplateModelException {
        if (arguments != null && !arguments.isEmpty() && arguments.get(0) != null && StringUtils.isNotEmpty(arguments.get(0).toString())) {
            String message = null;
            String code = arguments.get(0).toString();
            if (arguments.size() > 1) {
                Object[] args = arguments.subList(1, arguments.size()).toArray();
                message = SpringUtils.getMessage(code, args);
            } else {
                message = SpringUtils.getMessage(code);
            }
            return new SimpleScalar(message);
        }
        return null;
    }

}

编写模板文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<title>Welcome!</title>
	</head>
	<body>
		<h1>Welcome ${user}!</h1>
		<p>Our latest product:
		<a href="${latestProduct.url}">${latestProduct.name}</a>!
		<p>${message("demo.test")}</p>
	</body>
</html>



以下,将模板静态化成html界面即可

@Service("staticService")
public class StaticServiceImpl implements IStaticService, ServletContextAware {
	
	private ServletContext servletContext;
	@Resource(name="freeMarkerConfigurer")
	private FreeMarkerConfig freeMarkerConfig;
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	

	@Override
	public void build() {
		
                /* 创建数据模型 */
                Map<String, Object> root = new HashMap<String, Object>();
                root.put("user", "Big Joe");
                Map<String, String> latest = new HashMap<String, String>();
                root.put("latestProduct", latest);
                latest.put("url", "products/greenmouse.html");
                latest.put("name", "green mouse");

		FileOutputStream fileOutputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		Writer writer = null;
		
		try {
			String staticPath = "/static/test.html";
			
			String templateFileName = "test.ftl";
			//String templateDir = "/WEB-INF/template";
			String templatePath = "/test.ftl";
			
			File originalFile = new File(servletContext.getRealPath(staticPath));
			if (originalFile.exists()) {
				originalFile.delete();
			}
			
			Template template = freeMarkerConfig.getConfiguration().getTemplate(templatePath);
			/*Configuration cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(servletContext.getRealPath(templateDir)));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			Template template = cfg.getTemplate(templateFileName);*/
			
			File staticFile = new File(servletContext.getRealPath(staticPath));
			
			fileOutputStream = new FileOutputStream(staticFile);
			outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
			writer = new BufferedWriter(outputStreamWriter);
			template.process(map, writer);
			writer.flush();
			System.out.println("-----静态化成功------:"+staticFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}


}




阅读更多

Spring+freemarker 国际化的问题

04-17

我今天参加了这个blogrnhttp://www.blogjava.net/liuwentao253/archive/2007/09/23/147563.htmlrn 做了下Spring+freemarker 国际化 但是失败了, 请大家先看看那个博客的内容。rnrn我首先报的错是:rnError reading imported file includes/spring.ftlrnThe problematic instruction:rn----------rn==> import "/index/spring.ftl" as spring [on line 1, column 1 in ok.html]rn----------rnrnJava backtrace for programmers:rn----------rnfreemarker.template.TemplateException: Error reading imported file index/spring.ftlrn at freemarker.core.LibraryLoad.accept(LibraryLoad.java:122)rn at freemarker.core.Environment.visit(Environment.java:196)rn at freemarker.core.MixedContent.accept(MixedContent.java:92)rn at freemarker.core.Environment.visit(Environment.java:196)rn at freemarker.core.Environment.process(Environment.java:176)rn.....rnCaused by: java.io.FileNotFoundException: Template index/spring.ftl not found.rn at freemarker.template.Configuration.getTemplate(Configuration.java:489)rn at freemarker.core.Environment.getTemplateForInclusion(Environment.java:1357)rn at freemarker.core.Environment.getTemplateForImporting(Environment.java:1411)rn at freemarker.core.LibraryLoad.accept(LibraryLoad.java:112)rn ... 119 morernrn这个错说 没有找到spring.ftl rnrnrn我修改成我的模板文件头部rn<#import "spring.ftl" as spring/>rnrn修改了之后就找到了。但是报的错是:rnrnrnError reading imported file index/spring.ftlrnThe problematic instruction:rn----------rn==> import "/index/spring.ftl" as spring [on line 1, column 1 in ok.html]rn----------rnrnJava backtrace for programmers:rn----------rnfreemarker.template.TemplateException: Error reading imported file index/spring.ftlrn at freemarker.core.LibraryLoad.accept(LibraryLoad.java:122)rn at freemarker.core.Environment.visit(Environment.java:196)rn at freemarker.core.MixedContent.accept(MixedContent.java:92)rn at freemarker.core.Environment.visit(Environment.java:196)rn at freemarker.core.Environment.process(Environment.java:176)rn at freemarker.template.Template.process(Template.java:232)rn at com.cgt.itspiderman.action.test.StaticFreemarker.init(StaticFreemarker.java:40)rn at com.cgt.itspiderman.action.test.PersonAction.save(PersonAction.java:58)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:597)rn at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)rn at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)rn at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)rn at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)rn at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)rn at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)rn at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)rn at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:123)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)rn at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)rn at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:186)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)rn at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)rn at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:105)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)rn at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)rn at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:83)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)rn .............rnCaused by: java.io.FileNotFoundException: Template index/spring.ftl not found.rn at freemarker.template.Configuration.getTemplate(Configuration.java:489)rn at freemarker.core.Environment.getTemplateForInclusion(Environment.java:1357)rn at freemarker.core.Environment.getTemplateForImporting(Environment.java:1411)rn at freemarker.core.LibraryLoad.accept(LibraryLoad.java:112)rn ... 119 morernrnError reading imported file index/spring.ftlrnThe problematic instruction:rn----------rn==> import "/index/spring.ftl" as spring [on line 1, column 1 in ok.html]rn----------rnrnJava backtrace for programmers:rn----------rnfreemarker.template.TemplateException: Error reading imported file index/spring.ftlrn at freemarker.core.LibraryLoad.accept(LibraryLoad.java:122)rn at freemarker.core.Environment.visit(Environment.java:196)rn at freemarker.core.MixedContent.accept(MixedContent.java:92)rn at freemarker.core.Environment.visit(Environment.java:196)rn............rnrnrn我的applicationContext.xmlrn[code=Java]rn rn rn rn messagesrn rn rn rn[/code]rnrnrnmessages.properties 和messages_zh_CN.properties 内容都是如下rntitle=SpringTestrnheading=Spring :: Testrngreeting=Hello, It is now rnrn模板的内容和那个博客里的内容是一样的

spring+freemarker使用出错求解

10-25

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'viewResolver' defined in ServletContext resource [/WEB-INF/spring-config.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: freemarker/core/ParseExceptionrn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:883)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)rn java.security.AccessController.doPrivileged(Native Method)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)rn org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)rn org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)rn org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)rn org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)rn org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)rn org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)rn org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)rn org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)rn org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:402)rn org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:316)rn org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:282)rn org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126)rn javax.servlet.GenericServlet.init(GenericServlet.java:211)rn org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)rn org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)rn org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)rn org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)rn org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)rn org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)rn org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)rn java.lang.Thread.run(Unknown Source)rnroot causernrnjava.lang.NoClassDefFoundError: freemarker/core/ParseExceptionrn java.lang.Class.forName0(Native Method)rn java.lang.Class.forName(Unknown Source)rn org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver.class$(FreeMarkerViewResolver.java:57)rn org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver.requiredViewClass(FreeMarkerViewResolver.java:57)rn org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver.(FreeMarkerViewResolver.java:49)rn sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)rn sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)rn sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)rn java.lang.reflect.Constructor.newInstance(Unknown Source)rn org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:100)rn org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)rn java.security.AccessController.doPrivileged(Native Method)rn org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)rn org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)rn org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)rn org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)rn org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)rn org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)rn org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)rn org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)rn org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)rn org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:402)rn org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:316)rn org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:282)rn org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126)rn javax.servlet.GenericServlet.init(GenericServlet.java:211)rn org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)rn org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)rn org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)rn org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)rn org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)rn org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)rn org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)rn java.lang.Thread.run(Unknown Source)

没有更多推荐了,返回首页