猪猪吧博客2 技术 JAVA 正文

springboot 实现静态化html

Application中添加:

public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myHtmlInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
}

@Bean
public HtmlInterceptor myHtmlInterceptor(){
return new HtmlInterceptor();
}
/**
* 增加自定义视图变量和方法
*
* @return
*/
@Bean
public CommandLineRunner customFreemarker(FreeMarkerViewResolver resolver) {
return new CommandLineRunner() {
@Override
       public void run(String... strings) throws Exception {
//增加视图
           resolver.setViewClass(FreemarkerViewUtil.class);
//添加自定义解析器
           //Map map = resolver.getAttributesMap();
           //map.put("conver", new MyConver());
       }
};
}





HtmlInterceptor.java


import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;

/**
* 站点静态化,如果有生成好的html,那么直接返回html页面
**/
@Component
public class HtmlInterceptor implements HandlerInterceptor {
private static final HashMap<String, String> HTML_MAPPING = new HashMap<String, String>();

@Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
//请求的 url 地址
       String urlBrow = request.getServletPath();
String htmlUrl = HTML_MAPPING.get(urlBrow);
if (null != htmlUrl && htmlUrl.length() > 0) {
File file = new File(request.getSession().getServletContext().getRealPath("") + htmlUrl);
if (file.exists()) {
request.getRequestDispatcher(htmlUrl).forward(request, response);
return false;
}
}
//静态文件地址
       String filePath = request.getSession().getServletContext().getRealPath("/");
StringBuffer fileName = new StringBuffer(urlBrow+ ".html");
String savePath = filePath + "html" + File.separator + fileName.toString().replace("/",File.separator);
HTML_MAPPING.put(urlBrow.toString(), "/html" + fileName);
request.setAttribute("savePath", savePath);
return true;
}

@Override
   public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

}

@Override
   public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

}
}


FreemarkerViewUtil.java 

import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Locale;
import java.util.Map;

public class FreemarkerViewUtil extends FreeMarkerView {
@Override
   protected void doRender(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// 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() + "'");
}
// Grab the locale-specific version of the template.
       Locale locale = RequestContextUtils.getLocale(request);
if (null != request.getAttribute("savePath") && String.valueOf(request.getAttribute("savePath")).length() > 0) {
createHTML(getTemplate(locale), fmModel, String.valueOf(request.getAttribute("savePath")), response);
}
processTemplate(getTemplate(locale), fmModel, response);
}


public void createHTML(Template template, SimpleHash model, String filePath,
HttpServletResponse response) throws IOException, TemplateException, ServletException {
File htmlFile = new File(filePath);
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();

}
}


本文转载自互联网,版权归原作者所有,转载目的在于传递更多的信息,并不代表本网站的观点和立场。 如发现本站文章存在内容、版权或其它问题,烦请联系,我们将及时删除。

评论列表

    快捷回复: