Integration of SPRINGMVC with Freemarker and multi-view parser configuration

Source: Internet
Author: User
Tags type null

One, Spring MVC view Parser

The workflow of the view parser is roughly the same: when a controller's method executes, it returns a view (for example: Listuser), and the job of the view parser is to find an object

To finish rendering the view, or jump to a different logical view. The rendering object here is usually our JSP file or the Freemarker we use below (for example, listuser.jsp or

LISTUSER.FTL). After rendering is complete, the parsing results are sent to the client browser.

The following is a description of the parser used in this article (for more parser data, please refer to http://e-freya.iteye.com/blog/384083):

Internalresourceviewresolver: This is one of the most commonly used parsers. It is typically used to specify the render object as a JSP page.

Freemarkerviewresolver: This is the parser that spring and freemarker need to integrate.

Second, detailed configuration:

1.web.xml

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "> <display-name> Springmvcfreemarker</display-name> <servlet> <servlet-name>dispatcherservlet</servlet-name    > <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> &LT;PARAM-VALUE&GT;/WEB-INF/APPL icationcontext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </ servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern >*.do</url-pattern> </servlet-mapping> <welcome-file-list> <Welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> < Welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> < Welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </ Welcome-file-list></web-app>

2.applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" 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:context=" Http://www.springframework.org/schema/context "Xsi:schem alocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans . 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-MV C.xsd "> <!--Universal View Resolver--<bean id=" Viewresolvercommon "class=" ORG.SPRINGFRAMEWORK.WEB.SERVL Et.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf/page/"/> <p Roperty name= "suffix" value= ". jsp"/> <!--can be empty, easy to implement its own according to the extension to select the View Interpretation class logic--<property name= "Viewclass" > <value>org.sprin gframework.web.servlet.view.internalresourceview</value> </property> <property name= "Orde R "value=" 1 "/> </bean> <!--configuration Freemarker View Resolver--<bean id=" VIEWRESOLVERFTL "class= "Org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" > <property name= "Viewclass" value= "Org.springframework.web.servlet.view.freemarker.FreeMarkerView"/> <property name= "ContentType" value= "text /html;  Charset=utf-8 "/> <property name=" Cache "value=" true "/> <property name=" suffix "value=". FTL "      /> <property name= "order" value= "0"/> </bean> <!--configuration Freemarker template path--          <bean id= "Freemarkerconfig" class= "Org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" > <property Name= "Templateloaderpath" > <value>/WEB-INF/ftl/</value> </property> &LT;PR Operty name= "Freemarkervariables" > <map> <entry key= "Xml_escape" value-ref= "Fmxm              Lescape "/> </map> </property> <property name=" defaultencoding ">              <value>utf-8</value> </property> <property name= "Freemarkersettings" > <props> <prop key= "Template_update_delay" >3600</prop> </prop s> </property> </bean> <bean id= "Fmxmlescape" class= "Freemarker.template.utili Ty. Xmlescape "/> <!--annotations Support-<mvc:annotation-driven/> <!--scan all classes in the package to complete the BEA n Create and auto-dependent injection features-<context:component-scan base-package= "Dhp.springmvc.freemarker" > <!--allows the definition of filters to         Some classes under the base package are included or excluded <context:include-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/>---& Lt;/context:component-scan> </beans>


3.UserController

Package Dhp.springmvc.freemarker;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import org.springframework.web.bind.annotation.requestmapping;@ Controller@requestmapping ("/freemarker") public class Usercontroller {@RequestMapping ("/hello") public    String SayHello (Modelmap map) {        System.out.println ("Say Hello ...");        Map.addattribute ("name", "world!");        return "/hello";    }        @RequestMapping ("/hi") public    String Sayhi (Modelmap map) {        System.out.println ("Say hi ...");        Map.put ("Name", "JoJo");        return "/hi";    }        @RequestMapping ("/jsp") public    String jsprequest (Modelmap map) {        System.out.println ("Jsprequest ...");        Map.put ("name", "JSP");        return "/temp";    }}

In the view resolver there is a <property name= "order" value= "OrderValue"/> Configuration, which represents the priority level of the parser. We set the Freemarkerviewresolver level to 0 and the internalresourceviewresolver level to 1. In this way, the parser will first use Freemarkerviewresolver for parsing, if the corresponding template can not be found, the use of Internalresourceviewresolver to parse, if you can not find the page, will produce a 404 error!

In this example, we have a temp.jsp page under/web-inf/page/with a template file for HELLO.FTL and HI.FTL under/web-inf/ftl/. So when you visit Freemarker/hello, orFreemarker/hi,controller returns a View object that is parsed using Freemarkerviewresolver, based on the parser configuration. It will be based on the configuration of the template path Templateloaderpath/web-inf/ftl/to find out if there is a Hello and hi and configure the suffix value in the suffix. FTL, i.e.Hello. FTL and HI.FTL files, if found, use this template for parsing.


when a user accesses freemarker/jsp , return to the temp view, the first to use Freemarkerviewresolver to parse, the results found in/web-inf/ftl/ Under and did not TEMP.FTL this template file, so use Internalresourceviewresolver to parse, so began to look for/web-inf/page/under Showuser.jsp file. Since we have created this file, we end up using temp.jsp for rendering. Then if the temp.jsp is not found, a 404 error will be thrown.

It is also important to note that if the controller returns a view with a suffix JSP or FTL, do not join the suffix configuration in the configuration, otherwise the page will not be found.


Report:

Freemarker Common syntax

There are two types of freemarker interpolation: 1, universal interpolation ${expr};2, numeric formatting interpolation: #{expr} or #{expr;format}

${book.name?if_exists}//For judging if present, output this value

${book.name?default (' xxx ')}//default value XXX
${book.name! " XXX "}//default value XXX
${book.date?string (' Yyyy-mm-dd ')}//Date format
${book?string.number} 20//three different number formats
${book?string.currency}--<#--$20.00--
${book?string.percent}-<#--20%--


< #assign foo=ture/>//declaring variables, inserting Boolean values for display
${foo?string ("Yes", "No")} <#--Yes-


The size comparison symbol usage needs to be noted: (Reason for XML), which can be used to compare numbers and dates
Use LT, LTE, GT, and GTE to replace <, <=, >, and >= can also use parentheses < #if (x>y) >


Built-in functions: Calls are distinguished from the properties of the access, using the? instead.
Some of the common built-in functions
for string
html-HTML encoding of strings
Cap_first-to capitalize the first letter of a string
lower_case-to convert a string to lowercase
trim-remove whitespace characters before and after a string


Example: ${"Freemarker"? Cap_first}





For sequences (sequence)
Size-gets the number of elements in the sequence


For digital
Int-gets the integer part of the number (as the result of -1.9?int is-1)


For collections, you can use an array to access it using the subscript index


Logical judgment:
If ....... .....


< #if Condition&gt, .....
< #elseif Condition2&gt, .....
< #elseif Condition3&gt, .....
< #else, .....
Boolean-type null-value judgment
Empty value can be written as < #if book.name?? >//Note ${} is the rendering of the variable, and <> is defined as the definition of the operator


Switch .......
< #switch value>
< #case refvalue1>
...
< #break >
< #case refvalue2>
...
< #break >
...
< #case refvaluen>
...
< #break >
< #default >
...
</#switch >


Quickly define a collection of int intervals
< #assign l=0..100/>//attention not required []


3: Loop-Read collection: note/use
< #list student as Stu>
${stu}<br/>
</#list >
Similar to the JSTL loop, you can also access the state of the loop
Item_index: Index value of the current variable
Item_has_next: Whether there is a next object where the item name is called as after the variable name, such as Stu


Set length judgment
< #if student?size! = 0></#if > Judging =, note that only one = symbol, not = =


Macros/Templates
Preliminary understanding: Use more like a closure closure, can be defined, referenced anywhere in the script, and work in situ
< #macro greet>
<font size= "+2" >hello joe!</font>
</#macro >
This is used in the following ways:
< @greet ></@greet >//XML can be abbreviated to < @greet/>


Macro parameter definition, similar to JS, after the macro name with parameters to pass the definition
< #macro greet person color>
${person}
</#macro >


When calling with parameters, pay attention to using XML-like attribute formats for delivery, without concern for order issues
< @greet person= "Fred" color= "Black"/>


Parameter default value definition, if not, must be required to pass the complete argument list
< #macro greet person color= "BLACK" >
<font size= "+2" color= "${color}" >hello ${person}!</font>
</#macro >


Use nested content of XML for delivery of macro calls, key tags < #nested >
< #macro border>
<table border=4 cellspacing=0 cellpadding=4><tr><td>
< #nested >
</tr></td></table>
</#macro >


When called:
< @border >the bordered text</@border >


< #nested > tags can be called multiple times in a macro, or multiple macro combinations can be nested


Lite version of For loop:
< #list 1..count as x>
</#list >


The loop variable of the macro, with the nested label for parameter passing,
< #macro repeat count>
< #list 1..count as x>
< #nested x, X/2, x==count>//Three parameters here, will be passed to the nested content
</#list >
</#macro >


< @repeat count=4; C, HALFC, last>
${c}. ${halfc}< #if last> last!</#if >//The content here consists of the macro < #nested > The transfer of the number of parameters, when attention needs to accept these
</@repeat >
The use of the above also requires attention;


The number of parameters is variable, not all are required, but the effect is different


Defining variables in Templates
There are three types of variables defined in the template:
Plain variables: can be accessed anywhere in the template, including templates inserted using the include directive, created and replaced with assign directives.
Local variables: Valid in the macro definition body, created and replaced with local directives.
Loop variable: A nested content that can exist only in a directive, created automatically by an instruction (such as list); A macro's argument is a local variable, not a loop variable


< #assign x = "plain" >//Global plain variable
The internal loop variable will hide the external loop variable with the same name


Use of external imports, can be used for modularity, and provides common
such as: LIB/MY_LIB.FTL file
< #macro Copyright date>
<p>copyright (C) ${date} Julia Smith. All rights reserved.
<br>email: ${mail}</p>
</#macro >
< #assign mail = "[email protected]" >


LIB/MY_INC.FTL file
< #import "/LIB/MY_TEST.FTL" as my>
< #assign mail= "[email protected]" >
< @my. Copyright date= "1999-2002"/>
${my.mail}
${mail}
There will be no conflict between output results


For variable modifications in the library, use the IN keyword
< #assign mail= "[email protected]" in my>


function definition: Different from macro object, with return value
< #function name param1 param2>< #return val></#function > function, with return parameters


Stringa[m. N] substring, similar to substring (Stringa, M, N)


< #include "/copyright_footer.html" > Import other page elements
< #include filename options>
Options contains two properties
encoding= "GBK" encoding format
Whether Parse=true is parsed as an FTL syntax, the default is that True,false is introduced as text. Note that the Ribble value in the FTL file is directly assigned as Parse=true, not


Parse= "true"


Definition of hash and list
< #assign c= {"A": "Orz", "B": "CZs"}>
${C.A}


A list fragment can be defined using the format of: products[10..19] or products[5.
< #assign c= [1,2,3,4,5,6,6,7]>
< #list c[1..3] as v>
${V}
</#list >


Default handling of variables
product.color! " Red


Use Compress directive or transform to process the output.
< #compress >...</#compress;: Eliminate blank lines.
< @compress single_line=true>...</@compress > compresses the output to one line. Requires documentation for the package


Freemarker available "[" instead of "<". Add [#ftl] at the beginning of the file of the template.


Comments section
<#--comments section--


A different way of digital output
#{c.a;m0} is distinguished from ${}, this example is used to format the output numbers, preserving the number of decimal places, as detailed below


Numeric formatting interpolation can be formatted with #{expr;format}, where format can be:
MX: Decimal part min x bit
MX: Fractional part max x bit


When defining a string, you can use ' or ', for special characters, to escape with \


If there are a number of special characters, you can use ${r "..." to filter
${r "${foo}"}
${r "C:\foo\bar"}


The key and value of the map object are expressions, but key must be a string
can be mixed with. and ["] Access
book.author["name"]//mixed use point syntax and square brackets syntax


To handle missing variables, Freemarker provides two operators: exceptions to prevent objects from being present
!: Specify default values for missing variables
??: Determines whether a variable exists, returns a Boolean value


The noparse directive specifies that Freemarker does not process the content contained in the specified directive, which has the following syntax format:
< #noparse >...</#noparse >


${firstname?html} formatting characters with HTML, filtering for <, etc.


Escape, noescape directive, a practical and unified expression of the contents of the body
Look at the following code:
< #escape x as x?html>
First Name:${firstname}
Last Name:${lastname}
Maiden Name:${maidenname}
</#escape >
The above code is equivalent to:
First name:${firstname?html}
Last name:${lastname?html}
Maiden name:${maidenname?html}


How to define global variables
< #assign name1=value1 Name2=value2/>//You can define multiple variables at the same time, or you can use loops to assign values to variables
< #assign x>
< #list ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] as N>
${n}
</#list >
</#assign >
${X}


Setting instructions for dynamically setting the Freemarker environment:


This instruction is used to set the operating environment of the Freemarker, the syntax format of the directive is as follows:< #setting Name=value> In this format, the value range of name includes the following:
Locale: This option specifies the country/language options used for the template
Number_format: Specifies the format of the formatted output number
Boolean_format: Specifies the syntax format for two Boolean values, the default value is True,false
Date_format,time_format,datetime_format: Specifies the format of the formatted output date
Time_zone: Set the time zone to use when formatting the output date


< #return > Run to exit a macro


HTML is used to filter the HTML characters that may be contained in a string.


Calling the Java method requires implementing the Templatemethodmodel interface, but it seems to overwrite the access of the property



Integration of SPRINGMVC with Freemarker and multi-view parser configuration

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.