1. 程式人生 > >SpringMVC整合FreeMarker產生模板檢視

SpringMVC整合FreeMarker產生模板檢視

引入包:

<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.20</version>
		</dependency>
第一次引入的包groupId為freemarker,版本2.3.8,報錯,改為org.freemarker正常。

配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.1.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
		http://www.springframework.org/schema/util
		http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	<!-- 掃描的包 -->
	<context:component-scan base-package="com.smart.web"/>
	
	
	<!-- HandlerMapping和HandlerAdapter及資料轉換器配置 -->	
    <mvc:annotation-driven conversion-service="conversionService">
    	<mvc:message-converters register-defaults="true">
    		<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
       		<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"
                p:marshaller-ref="xmlMarshaller" p:unmarshaller-ref="xmlMarshaller">
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    	</mvc:message-converters>
    </mvc:annotation-driven>
    <!-- 資料轉換器 -->
	<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
		<property name="converters">
			<list>
				<bean class="com.smart.domain.StringToUserConvert" />
			</list>
		</property>
	</bean>      
	 <!-- xml訊息轉換器 -->         
    <bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
        <property name="streamDriver">
            <bean class="com.thoughtworks.xstream.io.xml.StaxDriver"/>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.smart.domain.User</value>
            </list>
        </property>
    </bean>   
           
    
	<!-- 在使用Excel/PDF/XML的檢視時,請先把這個檢視解析器註釋掉,否則產生檢視解析問題-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:order="100" p:viewClass="org.springframework.web.servlet.view.JstlView"
          p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>
	
	<!-- FreeMarker基礎設施及檢視解析器配置 -->
	<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
		 p:templateLoaderPath="/WEB-INF/ftl" 
		 p:defaultEncoding="UTF-8">
		 <property name="freemarkerSettings">
            <props>
                <prop key="classic_compatible">true</prop>
            </props>
        </property>
	</bean>
  	<bean  class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"
            p:order="5" p:suffix=".ftl" p:contentType="text/html; charset=utf-8"/>
</beans>

order指定的優先順序中,freeMarker檢視高於InternalResource檢視,所以系統使用freeMarker解析檢視。

介面:

package com.smart.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smart.domain.User;

@Controller
@RequestMapping("/sp4")
public class Sp4Controller {
	@RequestMapping(value="m1",method=RequestMethod.GET)
	@ResponseBody
	public String m1(){
		return "inm1";
	}
	
	@RequestMapping(value = "/m2",method=RequestMethod.POST)
	public ResponseEntity<User> m2(HttpEntity<User> requestEntity) throws UnsupportedEncodingException {
		User user = requestEntity.getBody();
		System.out.println("######:"+user+"---"+user.getRealName());
		user.setUserId("1000");
		return new ResponseEntity<User>(user, HttpStatus.OK);
	}
	
	@RequestMapping(value="/m3",method=RequestMethod.GET)
	public String m3(ModelMap mm){
		List<User> list = new ArrayList<User>();
		User user = new User();
		user.setUserId("1");
		user.setUserName("zhangsan");
		list.add(user);
		User user1 = new User();
		user1.setUserId("2");
		user1.setUserName("lisi");
		list.add(user1);
		mm.addAttribute("list", list);
		return "suc";
	}
	
	@RequestMapping(value="/m4" ,method=RequestMethod.GET)
	public String m4(ModelMap mm){
		List<User> list = new ArrayList<User>();
		User user = new User();
		user.setUserId("1");
		user.setUserName("zhangsan");
		list.add(user);
		User user1 = new User();
		user1.setUserId("2");
		user1.setUserName("lisi");
		list.add(user1);
		mm.addAttribute("userList", list);
		return "userFtl";
	}
	
}

m4方法;

模板,和配置對應,在/WEB-INF/ftl  下建立 userFtl.ftl檔案

<#import "spring.ftl" as spring />
<html>
	<head>
		<title>smart</title>
	</head>
	<body>
		使用者列表
		<table>
           <#list userList as user>
				<tr>
					<td>
					   <a href="<@spring.url '/user/showUser/${user.userName}.html'/>">  
					    ${user.userName}
					   </a>
					</td>
			        <td>${user.userId}</td>
			        <td>${user.userId}</td>    
				</tr>
           </#list>
		 <table>
	</body>
</html>

這裡使用spring定義的巨集,<@spring.url '/user/showUser/${user.userName}.html'/>產生的路徑為相對於專案專案部署路徑。