标签:freemarker实例
由于项目需要,需要使用FreeMarker ,今天正好研究就写了一个简单的小例子
首先配置web.xml,
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.from</url-pattern> </servlet-mapping>
然后配置applicationContext.xml
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/pages/" /> <property name="freemarkerSettings"> <props> <prop key="defaultEncoding">GBK</prop> </props> </property> </bean> <bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="cache" value="true" /> <property name="prefix" value="" /> <property name="suffix" value=".ftl" /> <property name="order" value="1" /> <property name="contentType"> <value>text/html;charset=GBK</value> </property> </bean>
接着需要写一个简单的实体类(省略),以及一个Controller
@Controller @RequestMapping("/demo") public class TestController { @RequestMapping("/test.from") public String test(Model model){ List<Users> list = new ArrayList<Users>(); Users user1 = new Users(); user1.setId(1); user1.setUserName("任飘渺"); user1.setGender("男"); user1.setSal(5000.0); Users user2 = new Users(); user2.setId(2); user2.setUserName("文荒"); user2.setGender("男"); user2.setSal(5000.0); Users user3 = new Users(); user3.setId(3); user3.setUserName("任风歌"); user3.setGender("男"); user3.setSal(5000.0); Users user4 = new Users(); user4.setId(4); user4.setUserName("陨落"); user4.setGender("男"); //user4.setSal(5000.0); 测试空值处理 list.add(user1); list.add(user2); list.add(user3); list.add(user4); model.addAttribute("username", "slayers") .addAttribute("pwd", "123456").addAttribute("userlist",list); return "user"; }
之后的就需要我们写一个ftl文件 user.ftl
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> </head> <body> welcome ${username}! Your PWD is ${pwd}<br/> <div> <table> <#list userlist as user> <tr><td>编号:</td><td><input type="text" value="${(user.id)!}" /></td></tr> <tr><td>姓名:</td><td><input type="text" value="${(user.userName)!}" /></td></tr> <tr><td>性别:</td><td><input type="text" value="${(user.gender)!}" /></td></tr> <tr><td>薪水:</td><td><input type="text" value="${(user.sal)!}" /></td></tr> </#list> </table> </div> </body> </html>
这样一个简单的实例就完成了 上面的ftl中 对空值 做了${(xxx)!}这种方式的处理以免又是报错
标签:freemarker实例
原文地址:http://slayers.blog.51cto.com/4112691/1543543