SpringMVC and freemarker Integration

Source: Internet
Author: User

SpringMVC and freemarker Integration

FreeMark

FreeMarker is a Java template engine that generates text output based on the template. FreeMarker has nothing to do with the Web Container, that is, when the Web is running, it does not know Servlet or HTTP. It can not only be used as the Implementation Technology of the presentation layer, but also be used to generate XML, JSP or Java.

Features

GeneralCan generate various texts: HTML, XML, RTF, Java source code, and so on. Easy to embed into the product: lightweight; no Servlet environment is required. Plug-in template Loader: you can load templates from any source, such as local files and databases. You can generate text as needed: Save it to a local file, send it as Email, and send it back to a Web browser from a Web application. Powerful template LanguageAll common commands: include, if/elseif/else, and loop structure. Create and change variables in the template. You can use a complex expression to specify a value almost anywhere. A named macro that can have location parameters and nested content. Namespace helps you create and maintain reusable macro libraries, or split a large project into modules without worrying about name conflicts. Output conversion block: HTML Escape, compression, and syntax highlighting are converted when a nested template segment generates an output. You can define your own conversion. General Data ModelFreeMarker does not directly reflect to Java objects. Java objects are encapsulated by plug-in objects and displayed in the template as variables. Abstract (Interface) can be used to represent objects (JavaBean, XML documents, SQL query result sets, etc.), telling template developers to use them. To avoid technical details. Prepare for WebBuilt-in structure for processing typical Web-related tasks (such as HTML escaping) in the template language. Can be integrated into the Model2 Web application framework as a substitute for JSP. Supports JSP tag libraries. Design for MVC mode: Separate visual design and application logic; Separate page designers and programmers. Intelligent internationalization and LocalizationIntelligent Character Set (UNICODE is used internally ). The digital format is sensitive to localization. Date and Time formats are sensitive to localization. Non-US character sets can be used as Identifiers (such as variable names ). The same template in multiple languages. Powerful XML processing capabilitiesThe <# recurse> and <# visit> commands (Version 2.3) are used to recursively traverse the XML tree.

Clearly and intuitively access the XML Object Model in the template.

Usage

Public class FreeMarker extends HttpServlet {private Configuration cfg; protected void doGet (HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {// create a 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); // obtain the Template file Template t = cfg. getTemplate ("message.html", "UTF-8 "); // start preparing to generate the output // use the charset of the template file as the charset of this page // use the text/html MIME-typeresponse.setContentType ("text/html; charset =" + t. getEncoding (); PrintWriter out = response. getWriter (); // combines data models and templates and outputs the results to try {t. process (map, out); // use a template to develop a servlet. You can only add dynamic data to the code.} catch (TemplateException e) {throw new ServletException ("error occurred in Template processing", 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 the position of the FreeMarker template file cfg. setServletContextForTemplateLoading (getServletContext (),"");}}


This is a basic servlet, which is accessed through doGet and doPost. Servlet needs to be configured in the web. xml file, which is not described here.

To access this servlet, you must first initialize this method. Message.html

<# List Content as con> <# list con? Keys as mapkey>
  
  • $ {Con [mapkey]. IF_theme} $ {con [mapkey]. IF_time} Times of reading $ {con [mapkey]. IF_readNum}

    View full text
I will not detail the page



SpringMVC and FreeMarker Integration

SpringMVC configuration is not described here. Please use Baidu. The configuration of freemark is provided here.
        
         
             
                  
     
      0
                   
     
      UTF-8
                   
     
      0.##########
                   
     
      yyyy-MM-dd HH:mm:ss
                   
     
      true
                   
     
      ignore
               
          
     
    
SpringMVC can return data to a page in two ways: ModelAndView and 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;      }  
In the above Code, hello is the corresponding template file. The title and content on the page can be obtained directly through $ {title} and $ {content} $ {title !} In this way, the title does not have a value and an error is reported on the page. If no value is displayed after an exclamation point is added, ModelMap is not displayed.
public String doLogin(HttpServletRequest req,HttpServletResponse resp, ModelMap modelMap) throws Exception {modelMap.put("base", Constants.CONTEXTPATH);return "";}
I personally prefer ModelMap, which is easy to use. The page file (not filled here) after return is used. The prefix and suffix need to be configured in the spring configuration file. freemark didn't say ftl files are required, so other files can also be used.



How to access static Resources


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.