SSM 整合 freemaker,避免掉坑

it2022-05-05  305

搭建好SSM项目之后,整合freemaker其实很简单,总的来说就是三步: 1、导包

<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.6.RELEASE</version> </dependency>

2、配置 在springmvc的配置文件中添加:

<bean id="freeMarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/view/" /> <property name="freemarkerSettings"> <props> <prop key="output_encoding">UTF-8</prop> <prop key="default_encoding">UTF-8</prop> <prop key="number_format">#</prop> </props> </property> </bean> <bean id="freeMarkerResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="contentType" value="text/html;charset=utf-8" /> <property name="exposeRequestAttributes" value="true" /> <property name="requestContextAttribute" value="request" /> <property name="cache" value="true" /> <property name="prefix" value="" /> <property name="suffix" value=".html" /> </bean>

这里需要注意的是,如果配置了freemarker的视图解析器,就不需要再配置springmvc的视图解析器,因为会先加载springmvc的视图解析器,页面就不能通过freemarker获取值。 3、赋值,取值 在controller中给model添加属性:

@RequestMapping("hello") public String testFreemarker(Model model){ model.addAttribute("name","tom"); return "hello"; }

在页面上取值:`

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> 姓名: ${name} </body> </html>

页面效果:


最新回复(0)