Spring MVC整合FreeMarker的示例

什么是Freemarker?

FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
    目前企业中:主要用Freemarker做静态页面或是页面展示

一.工程结构

二.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>SpringMVC</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/springMVC-servlet.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

三.springMVC-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
          ">
  <!-- 自动扫描包 -->
  <context:component-scan base-package="com.bijian.study.controller"></context:component-scan>

  <!-- 默认注解映射支持 -->
  <mvc:annotation-driven></mvc:annotation-driven>

  <!--JSP视图解析器-->
  <bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
    <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
    <property name="order" value="1"/>
  </bean>

  <!-- 配置freeMarker视图解析器 -->
  <bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
    <property name="contentType" value="text/html; charset=UTF-8"/>
    <property name="exposeRequestAttributes" value="true" />
    <property name="exposeSessionAttributes" value="true" />
    <property name="exposeSpringMacroHelpers" value="true" />
    <property name="cache" value="true" />
    <property name="suffix" value=".ftl" />
    <property name="order" value="0"/>
  </bean>

  <!-- 配置freeMarker的模板路径 -->
  <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
    <property name="freemarkerVariables">
      <map>
        <entry key="xml_escape" value-ref="fmXmlEscape" />
      </map>
    </property>
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="freemarkerSettings">
      <props>
        <prop key="template_update_delay">3600</prop>
        <prop key="locale">zh_CN</prop>
        <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
        <prop key="date_format">yyyy-MM-dd</prop>
        <prop key="number_format">#.##</prop>
      </props>
    </property>
  </bean>

  <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
</beans>

在JSP和Freemarker的配置项中都有一个order property,上面例子是把freemarker的order设置为0,jsp为1,意思是找view时,先找ftl文件,再找jsp文件做为视图。这样Freemarker视图解析器就能与JSP视图解析器并存。

四.FreeMarkerController.java

package com.bijian.study.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.bijian.study.utils.JsonUtil;
import com.bijian.study.vo.User;

@Controller
public class FreeMarkerController {

  @RequestMapping("/get/usersInfo")
  public ModelAndView Add(HttpServletRequest request, HttpServletResponse response) {

    User user = new User();
    user.setUsername("zhangsan");
    user.setPassword("1234");

    User user2 = new User();
    user2.setUsername("lisi");
    user2.setPassword("123");

    List<User> users = new ArrayList<User>();
    users.add(user);
    users.add(user2);
    return new ModelAndView("usersInfo", "users", users);
  }

  @RequestMapping("/get/allUsers")
  public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {

    List<User> users = new ArrayList<User>();
    User u1 = new User();
    u1.setUsername("王五");
    u1.setPassword("123");
    users.add(u1);

    User u2 = new User();
    u2.setUsername("张三");
    u2.setPassword("2345");
    users.add(u2);

    User u3 = new User();
    u3.setPassword("fgh");
    u3.setUsername("李四");
    users.add(u3);

    Map<String, Object> rootMap = new HashMap<String, Object>();
    rootMap.put("userList", users);
    Map<String, String> product = new HashMap<String, String>();
    rootMap.put("lastProduct", product);
    product.put("url", "http://www.baidu.com");
    product.put("name", "green hose");

    String result = JSON.toJSONString(rootMap);

    Map<String, Object> resultMap = new HashMap<String, Object>();
    resultMap = JsonUtil.getMapFromJson(result);

    return new ModelAndView("allUsers", "resultMap", resultMap);
  }
}

五.JsonUtil.java

package com.bijian.study.utils;

import java.util.Map;

import com.alibaba.fastjson.JSON;

public class JsonUtil {

  public static Map<String, Object> getMapFromJson(String jsonString) {
    if (checkStringIsEmpty(jsonString)) {
      return null;
    }
    return JSON.parseObject(jsonString);
  }

  /**
   * 检查字符串是否为空
   * @param str
   * @return
   */
  private static boolean checkStringIsEmpty(String str) {
    if (str == null || str.trim().equals("") || str.equalsIgnoreCase("null")) {
      return true;
    }
    return false;
  }
}

六.User.java

ackage com.bijian.study.vo;

public class User {

  private String username;
  private String password;

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
}

七.usersInfo.ftl

<!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>usersInfo</title>
</head>
<body>
<#list users as user>
  <div>
    username : ${user.username},
    password : ${user.password}
  </div>
</#list>
</body>
</html>

八.allUsers.ftl

<html>
 <head>
  <title>allUsers</title>
 </head>
 <body>
  <#list resultMap.userList as user>
    Welcome ${user.username}!  id:${user.password}<br/>
  </#list>
  <p>Our latest product:
  <a href="${resultMap.lastProduct.url}" rel="external nofollow" >${resultMap.lastProduct.name} </a>!
 </body>
</html>

九.运行效果

再输入http://localhost:8088/SpringMVC/greeting?name=zhangshan,JSP视图解析器运行依然正常。

至此,就结束完成整合了!

以上就是Spring MVC整合FreeMarker的示例的详细内容,更多关于Spring MVC整合FreeMarker的资料请关注我们其它相关文章!

(0)

相关推荐

  • 构建SpringBoot+MyBatis+Freemarker的项目详解

    现在的Java web项目已经更多的使用SpringBoot来构建了,一个是他的配置更加简单,第二个是现在流行的为服务架构Springcloud就是基于SpringBoot来实现具体的技术细节的,MyBatis也是我们常用半自动式的持久层框架.今天小编就要带领大家一起搭建一个基于SpringBoot和MyBatis以及常用高性能页面渲染框架Freemarker来构建一个用户信息查询展示的项目. 生成项目架构文件.访问SpringBoot官网生成我们需要的Maven项目需要的文件.主要有一下几个选

  • spring boot加载freemarker模板路径的方法

    1,之前用的eclipse开发工具来加载spring boot加载freemarker模板路径,现在换用idea却不能使用了,所以来记录一下 加载freemarker模板三种方式,如下 public void setClassForTemplateLoading(Class clazz, String pathPrefix); public void setDirectoryForTemplateLoading(File dir) throws IOException; public void

  • Springboot整合Freemarker的实现详细过程

    基本配置.测试 1.导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> 2.准备一个Freemarker模板(.ftl) 3.注入Configuration对象(freemarker.template包下) 4.生成商品详情模

  • spring mvc整合freemarker基于注解方式

    基于网络改进为:最正常版本 复制代码 代码如下: <?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:p="htt

  • springmvc整合freemarker配置的详细步骤

    一.对应的导包(有些包是不必须的) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  • SpringBoot2.2.X用Freemarker出现404的解决

    之前看到SpringBoot出了2.2.1(目前2.2.2)版本,就跑了一下发现访问地址就是404,代码跟之前是一样的,只是我把以前的(2.1.8)版本升级了而已. 后来发现SpringBoot已经把原先默认的后缀名.ftl改成了.ftlh,如果想继续保持以前的.ftl就在配置文件中配置一下就好了. spring: freemarker: suffix: .ftl 遇到问题,做个记录. 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们.

  • 基于Freemarker和xml实现Java导出word

    前言 最近做了一个调查问卷导出的功能,需求是将维护的题目,答案,导出成word,参考了几种方案之后,选择功能强大的freemarker+固定格式之后的wordxml实现导出功能.导出word的代码是可以直接复用的,于是在此贴出,并进行总结,方便大家拿走. 实现过程概览 先在word上,调整好自己想要的样子.然后存为xml文件.保存为freemarker模板,以ftl后缀结尾.将需要替换的变量使用freemarker的语法进行替换.最终将数据准备好,和模板进行渲染,生成文件并返回给浏览器流. 详细

  • 后台使用freeMarker和前端使用vue的方法及遇到的问题

    一:freeMarker的使用 1:java后台使用freeMarker是通过Model,将值传给前端: 如: @Controller public class MobileNewsFreeMarkerController { @RequestMapping("page/test") public String Test(Model model,HttpServletRequest request){ //获取项目路径 String basePath = request.getSche

  • Spring MVC整合 freemarker及使用方法

    1.什么是Spring MVC? Spring MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将Web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,SpringMVC框架的目的就是帮助我们简化开发. Spring MVC 实现了即用的 MVC 的核心概念.它为控制器和处理程序提供了大量与此模式相关的功能.并且当向 MVC 添加反转控制(Inversion of Control,IoC)时,它使应用程序高度解耦,提供

  • Springboot整合freemarker 404问题解决方案

    今天遇到了ftl整合springboot出现的问题 @Controller public class IndexController { @RequestMapping("hello") public String index(){ System.out.println("aaa"); return "index"; } } 在浏览器输入 localhost:8080/hello 控制台也打印了aaa,index.ftl也写的没有问题.就是出现了

随机推荐