FreeMarker与SpringMVC整合

Posted on 2012-12-08 10:36 领悟书生 阅读(4462) 评论(1)  编辑  收藏

SpringMVC环境的搭建在这里就不多说了,我们这节主要是FreeMarker与SpringMVC整合

首先,在springmvc的配置文件普通视图之前,加入freemarker的视图

fre-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- 一定要放在viewResolver的前面,这样就先去找freemarker的 -->
<bean id="freemarkerConfig"
    class="org.springframework.web.servlet
          .view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
</bean>
<bean id="viewResolver"
    class="org.springframework.web.servlet
          .view.freemarker.FreeMarkerViewResolver">
    <property name="cache" value="true"/>
    <property name="prefix" value=""/>
    <property name="suffix" value=".ftl"/>
    <property name="contentType" value="text/html; charset=UTF-8"/>
</bean>
   
<bean
    class="org.springframework.web.servlet
          .view.InternalResourceViewResolver">
    <property name="viewClass"
          value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

控制器HelloController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package org. fre.controller;
  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
  
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("username""张三");
        return "hello";
    }
    @RequestMapping("/world")
    public String helloworld(Model model) {
        model.addAttribute("username","李四");
        return "world";
    }
}

在WEB-INF/jsp目录下有一个world.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        ${username }
    </body>
</html>

在WEB-INF/ftl目录下有

1
2
3
4
5
6
7
8
9
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>${username}</h1>
</body>
</html>

启动服务,

访问http://localhost:8080/hello时,显示张三

访问http://localhost:8080/world时,显示李四

到此就整合成功了


本文链接:FreeMarker与SpringMVC整合,本文由huangyineng原创,转载请注明出处
下一节:
FreeMarker在领悟教程网实战应用

Feedback

# re: FreeMarker与SpringMVC整合  回复  更多评论   

2014-05-16 21:38 by zuidaima
最代码转载地址:http://www.zuidaima.com/share/1825330654350336.htm

只有注册用户登录后才能发表评论。


网站导航: