欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring MVC配置 freemarker

程序员文章站 2022-07-12 19:27:38
...
配置spring MVC
<!-- freemarker start -->
		 <!--freemarker页面解析器 -->
		 <bean id="viewResolver"  class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		        <property name="suffix" value=".ftl"></property>
		        <property name="contentType" value="text/html;charset=UTF-8" />
		        <!-- 将Spring的FreeMarkerView改成我们扩展的View -->
		        <property name="viewClass" value="com.bm.biz.controller.MyFreeMarkerView" />
		        <property name="exposeRequestAttributes" value="true" />
		        <property name="exposeSessionAttributes" value="true" />
		        <property name="exposeSpringMacroHelpers" value="true" />
		        <property name="requestContextAttribute" value="request" />
		 </bean>
		<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />
		
		<!--配置Freemarker -->
		<bean id="freemarkerConfigurer"  class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		         <!-- 模版页面存放的位置 -->  
		        <property name="templateLoaderPath" value="/WEB-INF/ftl/"></property>  
		          <property name="templateLoaderPaths">
		              <list>
		                  <value>/WEB-INF/ftl/</value>
		              </list>
		          </property>
		        <property name="freemarkerSettings">
		            <props>
		            	<!-- 刷新间隔,秒 -->
		                <prop key="template_update_delay">20</prop>
		                <prop key="defaultEncoding">UTF-8</prop>
		                <prop key="auto_import">common/spring.ftl as spring</prop> <!-- spring 国际化相关 -->
		                <prop key="locale">zh_CN</prop><!-- 本地国际化 -->
		                <prop key="whitespace_stripping">true</prop>
						<prop key="boolean_format">true,false</prop>
		            </props>
		        </property>
		  </bean>
	<!-- freemarker end -->
如果能生成、但是转发不了 在spring里把生成的静态文件 放生
 <mvc:resources mapping="/staticPage/**" location="/staticPage/" />
注:spring MVC 配置视图的时候,在 freemarker 配置之后配置

package com.bm.biz.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

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

import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;


import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * 静态化
 * @author zjs
 * @date  2017年2月13日 15:43:50
 *
 */
public class MyFreeMarkerView extends FreeMarkerView{
    @Override
    protected void doRender(Map<String, Object> model,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
    	Locale locale = RequestContextUtils.getLocale(request);       
    	model.put("localeLan", locale);
        // Expose model to JSP tags (as request attributes).
        exposeModelAsRequestAttributes(model, request);
        // Expose all standard FreeMarker hash models.
        SimpleHash fmModel = buildTemplateModel(model, request, response);

        if (logger.isDebugEnabled()) {
            logger.debug("Rendering FreeMarker template [" + getUrl() + "] in FreeMarkerView '" + getBeanName() + "'");
        }

        /*
         * 默认生成静态文件,除非在编写ModelAndView时指定CREATE_HTML = false,
         * 这样对静态文件生成的粒度控制更细一点
         * 例如:ModelAndView mav = new ModelAndView("search");
         *       mav.addObject("CREATE_HTML", false);
         */
        if(Boolean.FALSE.equals(model.get("CREATE_HTML"))){
            processTemplate(getTemplate(locale), fmModel, response);
        }else{
            createHTML(getTemplate(locale),locale, fmModel, request, response);
        }
    }

    public void createHTML(Template template,Locale locale, SimpleHash model,HttpServletRequest request,
            HttpServletResponse response) throws IOException, TemplateException, ServletException {
    	   String fileName="";
           String requestURI = request.getRequestURI();
           String[] urlSplit = requestURI.split("/");
           for (String url : urlSplit) {
               fileName = fileName + url;
           }
           String staticPagePath = "/staticPage/" + fileName+"_"+locale+".html";
           // 静态页面绝对路径
           String basePath = request.getSession().getServletContext().getRealPath("/");
           String htmlPath = basePath + staticPagePath;
           System.out.println("htmlPath="+htmlPath);
           
            File htmlFile = new File(htmlPath);
            if(!htmlFile.getParentFile().exists()){
                htmlFile.getParentFile().mkdirs();
            }
            if(!htmlFile.exists()){
                htmlFile.createNewFile();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
            //处理模版 
            template.process(model, out);
            out.flush();
            out.close();
            /*将请求转发到生成的htm文件*/        
            request.getRequestDispatcher(staticPagePath).forward(request, response);

    }
    
	/**
	 * 计算要生成的<strong>静态</strong>文件相对路径.
	 */
	private String getRequestHTML(HttpServletRequest request) {

		//web应用名称,部署在ROOT目录时为空  
		String contextPath = request.getContextPath();

		//web应用/目录/文件.do  
		String requestURI = request.getRequestURI();

		//basePath里面已经有了web应用名称,所以直接把它replace掉,以免重复  
		requestURI = requestURI.replaceFirst(contextPath, "");
		//将请求改为.htm,稍后将请求转发到此htm文件  
		requestURI += ".htm";
		return requestURI;
	}

}
package com.bm.biz.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bm.biz.dao.UsUserMapper;



@Controller
@RequestMapping("/test")
public class TestController {
private static Logger log = Logger.getLogger(TestController.class);
//private static final Logger   logger = (Logger) LoggerFactory.getLogger(TestController.class); 
	
	@Autowired(required=true)
	@Qualifier(value="usUserMapper")
	private UsUserMapper usUserMapper;
	    

/*	@RequestMapping("test")
	@ResponseBody
	public Map<Object, Object> testJackson(Integer userId){
		Map<Object, Object> map = new HashMap<>();
		map.put("df", "敌法师");
		UsUser user = usUserMapper.selectByPrimaryKey(userId);
		log.error("+++++++++++++++++");
		log.info("-------------------------------------");
		log.info("sdfs");
		log.error("dds");
		System.out.println(JSON.toJSONString(user));
		return map;
		
	}*/
	
    @RequestMapping("index")  
    public ModelAndView index(){  
        ModelAndView modelAndView = new ModelAndView("test");  
        modelAndView.addObject("content", "网站标题-没生成");  
          
        //当设置false时不生成静态页面  
        modelAndView.addObject("STATIC_HTML", false);  
          
        return modelAndView;  
    }  
      
    
    @RequestMapping("testHtml")  
    public String test(Model model){  
    	model.addAttribute("content", "test Model");
    	return "test";  
    }
    
    
}
<#import "./common/spring.ftl" as spring />
<!DOCTYPE html>
<#--
<script type="text/javascript" src="./resources/jquery.min.js"></script>
-->

<body>
<#assign ctx=request.contextPath/>
${ctx}
<br>

${content}</body></html>
项目结构图:
Spring MVC配置 freemarker
            
    
    博客分类: freemarker

 

  • Spring MVC配置 freemarker
            
    
    博客分类: freemarker
  • 大小: 10.2 KB