FreeMarker与SpringMVC整合

摘要: SpringMVC环境的搭建在这里就不多说了,我们这节主要是FreeMarker与SpringMVC整合 首先,在springmvc的配置文件普通视图之前,加入freemarker的视图...

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

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

fre-servlet.xml

<!-- 一定要放在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

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

<%@ 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目录下有

<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与SpringMVC整合)