Spring MVC中如果只使用JSP做视图,可以使用下面这段即可解决:
<!-- 视图解释类 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean>
但很多时候我们需要的不只是JSP做view,可能会引用velocity、freemarker等做为view引擎时,需要加入额外的配置。
下面是在配置文件中加入Freemarker的方法,与JSP并存:
<!--JSP视图解析器--> <bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/> <property name="order" value="1"/> </bean> <!-- 配置freeMarker视图解析器 --> <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="exposeRequestAttributes" value="true" /> <property name="exposeSessionAttributes" value="true" /> <property name="exposeSpringMacroHelpers" value="true" /> <property name="cache" value="true" /> <property name="suffix" value=".ftl" /> <property name="order" value="0"/> </bean> <!-- 配置freeMarker的模板路径 --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/views/"/> <property name="freemarkerVariables"> <map> <entry key="xml_escape" value-ref="fmXmlEscape" /> </map> </property> <property name="defaultEncoding" value="UTF-8"/> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">3600</prop> <prop key="locale">zh_CN</prop> <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> <prop key="date_format">yyyy-MM-dd</prop> <prop key="number_format">#.##</prop> </props> </property> </bean> <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
在JSP和Freemarker的配置项中都有一个order property,上面例子是把freemarker的order设置为0,jsp为1。
意思是找view时,先找ftl文件,再找jsp文件做为视图。
测试:
Controller:
package com.my.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value="ftl") public class TestFreemarker { @RequestMapping(method=RequestMethod.GET) public ModelAndView index() { ModelAndView view = new ModelAndView("TestFreemarker/index"); view.addObject("message", "Say hi for Freemarker."); return view; } }
index.ftl:
<Html> <head> <title>${message}</title> </head> <body> <b>${message}</b> <body> </html>
输出: