SpringMVC 的 Controller 可以返回各种各样的视图。比如 JSP, JSON, Velocity, FreeMarker, XML, PDF, Excel, 还有Html字符流 等等。那它们该如何的进行处理的呢?这里就涉及到 各种视图(View)对应的各种视图解析器(ViewResolver). 基本上上面说的每一种视图就对应用一种视图解析器来处理。基本上各种视图解析器大致上可以分为两类:一是基于URL的视图解析器;一种是其它解析器;
<!-- jsp视图 --> <bean id="jspviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/views/"/> <property name="suffix" value=".jsp"/> <property name="order" value="1"></property> </bean> <!-- 配置freeMarker视图解析器(可解析HTML) --> <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=".html" /> <property name="order" value="0"/> </bean> <!-- 配置freeMarker的模板路径 --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/views/html/"/> <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>
需要在pom中引入jar包:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.4.RELEASE</version> </dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.22</version>
</dependency>
可能在启动时会报错:Caused by: java.lang.NoClassDefFoundError: org/springframework/ui/freemarker/FreeMarkerConfigurationFactory
需要引入spring-context-support.jar