首页 > 代码库 > spring使用freemarker

spring使用freemarker

 一、配置xml

  修改spring的初始化xml文件

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd  
            http://www.springframework.org/schema/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc.xsd  
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
      
    <!-- 配置freemarker -->  
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="http://www.mamicode.com/WEB-INF/pages/" />  
        <property name="freemarkerSettings">  
            <props><prop key="defaultEncoding">UTF-8</prop></props>  
        </property>  
    </bean>  
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="suffix" value="http://www.mamicode.com/.ftl" />  
        <property name="contentType" value="http://www.mamicode.com/text/html; charset=UTF-8" />  
    </bean>  
</beans>

  这个配置说明,Freemarker的模板文件放在/WEB-INF/pages/目录下,以.ftl后缀结束,如下图

技术分享

二、使用freemarker

  创建index.ftl和login.ftl两个文件,如上图,两个文件内容都只有一行,分别是index page和login page。

  创建一个controller

package org.demo.controller;  
  
import javax.servlet.http.HttpServletRequest;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@Controller  
public class SSOServerController {  
    @RequestMapping("/index")  
    public String index(HttpServletRequest req, Model model) {  
        return "index";  
    }
}  

  配置spring扫描controller。在spring配置文件中添加如下两行

<context:component-scan base-package="org.demo.controller" />  
<mvc:annotation-driven/>  

  启动项目,在浏览器访问

http://127.0.0.1:8080/index

spring使用freemarker