Freemark
Freemarker is a template engine written in the Java language that generates text output based on a template. Freemarker is not related to the Web container, that is, it does not know the servlet or HTTP while the web is running . It can be used not only as an implementation technique for the presentation layer, but also for generating xml,jsp or Java.
Characteristics
GeneralAbility to generate various types of text: HTML, XML, RTF, Java source code, and so on. Easy to embed in the product: lightweight, no servlet environment required. Plug-in Template loader: You can load templates from any source, such as local files, databases, and so on. You can generate text as desired: Save to a local file, send it as an email, and send it back to the Web browser from the Web application.
Powerful Template languageAll commonly used directives: include, if/elseif/else, loop structure. Create and change variables in the template. You can use complex expressions to specify values almost anywhere. A named macro that can have positional parameters and nested content. namespaces help you build and maintain reusable macro libraries, or divide a large project into modules without worrying about name collisions. Output Transform block: Transforms HTML escape, compression, syntax highlighting, and so on when generating output from nested template fragments; You can define your own transformations.
Common Data ModelThe freemarker is not reflected directly to the Java object, and the Java object is encapsulated in a plug-in object and is displayed in a template in a variable way. You can use abstract (interface) representations of objects (JavaBean, XML documents, SQL query result sets, and so on) to tell template developers to use them. method so that it is not disturbed by technical details.
preparing for the webThe structure of a typical web-related task, such as HTML escaping, is built into the template language. Can be integrated into the MODEL2 Web application framework as a substitute for JSPs. Support for JSP tag libraries. Design for MVC patterns: Separate visual design and application logic, separate page designers and programmers.
internationalization and localization of intelligenceCharacter Set intelligence (Unicode is used internally). The number format is localized sensitive. Date and time formats are localized sensitive. A non-US character set can be used as an identity (such as a variable name). The same template in many different languages.
powerful XML processing power< #recurse > and < #visit > directives (version 2.3) are used to recursively traverse an XML tree.
A clear and intuitive access to the XML object model in the template.
How to use
<pre name= "code" class= "Java" >public class Freemarker extends HttpServlet {private Configuration cfg;protected void Doget (HttpServletRequest req, httpservletresponse response) throws Servletexception, IOException {//Building data Model string page = req.getparameter ("page"); List root = Dataquery.dynamicquery ("", page); Map map = new HashMap (), Map.put ("Content", Root), Map.put ("page", dataquery.pagehtml (2, page));//Get template file Template T = cfg.g Ettemplate ("message.html", "UTF-8");//start preparing to generate output//Use CharSet of the template file as charset//for this page text/html Mime-typeresponse.setcontenttype ("text/html; charset= "+ t.getencoding ()); PrintWriter out = Response.getwriter ();//merge the data model and template, and output the results to out in try {t.process (map, out);// Using a template to develop a servlet can add Dynamic Data to the code only} catch (Templateexception e) {throw new Servletexception ("error occurred in processing template template", e);}} protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {doPost ( req, resp);} public void Init () throws Servletexception {//Initialize Freemarker configuration//Create a Configuration instance cfg = new Configuration ();//Set Freemarker template file Location cfg.setservletcontextfortemplateloading ( Getservletcontext (), "");}}
This is the basic servlet, accessed through Doget, Dopost. The servlet needs to be configured in the Web. xml file, which is not explained here, and some places are explained below.
This method is initialized first for access to the servlet. Message.html
< #list Content as con> < #list Con?keys as mapkey> <ul class= "Chatpanel" > <li class= "Media media Fulltext "> <a href=" "> <div class=" Mediapanel "> <div class=" mediahead "><span class= "title" >${con[mapkey]. If_theme}</span><span class= "Time" >${con[mapkey]. If_time}</span><span class= "Count" style= "Font-size:2px;color: #8C8C8C;" > Reading frequency ${con[mapkey]. if_readnum}</span> <div class= "CLR" ></div> </div> <div class= "mediaimg" & gt;</div> <div class= "Mediacontent mediacontentp" > <p></p> </div> <div class= "Mediafooter" > <span class= "Mesgicon right" ></span><span style= "Line-height:5 0px; "class=" Left > View full text </span> <div class= "CLR" ></div> </div> </div> </a> </li></#list ></#list >I won't go into details on this page.
SPRINGMVC and Freemarker Integration
SPRINGMVC configuration here also do not introduce, please own Baidu. Only the configuration of Freemark is given here.
<bean id= "Freemarkerconfig" class= "Org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" > <property name= "Templateloaderpath" value= "/web-inf/view/"/> <property name= " Freemarkersettings "> <props> <prop key=" Template_update_delay ">0</prop> < Prop key= "default_encoding" >UTF-8</prop> <prop key= "Number_format" >0.##########</prop> <prop key= "Datetime_format" >yyyy-mm-dd hh:mm:ss</prop> <prop key= "Classic_compatible" > true</prop> <prop key= "Template_exception_handler" >ignore</prop> </props> </property> </bean>
As for SPRINGMVC, there are two ways to pass data back to the page, one is Modelandview and the other is Modelmap.modelandview
Public Modelandview Freemark (HttpServletRequest req,httpservletresponse resp) throws Exception { Modelandview mv = New Modelandview ("Hello"); Mv.addobject ("title", "Spring MVC and Freemarker"); Mv.addobject ("Content", "Hello World, Test my first spring MVC!"); return MV; }
The hello in the code above is the corresponding template file, and the title and content can be obtained from the page directly via ${title} and ${content} ${title!} This can prevent the title from having no value and error in the page, plus no value after exclamation point will not show Modelmap
Public String dologin (httpservletrequest req,httpservletresponse resp, Modelmap modelmap) throws Exception { Modelmap.put ("base", Constants.contextpath); return "";}
Personal tend to modelmap, use more convenient, return is the page file (not filled in here), prefixes and suffixes need to be configured in the spring configuration file, Freemark does not say must be FTL file, so other files can also.
How to access static resources
SPRINGMVC and Freemarker Integration