静态页面生成那些事

来源:互联网 发布:swatch淘宝 编辑:程序博客网 时间:2024/04/20 11:00

相信在互联网企业或多或少都有一些需要生成静态页面的需求,下面就来谈谈我在项目里面遇到的生成静态页面的问题:

最初使用HttpUrlConnection指定URL向服务器发起一个连接请求,请求成功后从Connection对象获取输入流,然后将输入流内容写入指定的文件,开发阶段发布到测试服务器(内网)没有任何问题,但是发布到正式环境(公网)时则无法发布且不报任何错误,开始以为linux服务器文件写权限问题,但后面经过调试发现是获取网络输入流失败,估计是和网络设置有关,由于上线时间紧迫,就改为方式2!

方式1关键代码:

   URL url = new URL(httpUrl);
   
   connection = (HttpURLConnection) url
     .openConnection();
   connection.setRequestProperty("User-Agent", "Mozilla/4.0");

   connection.connect();


   in = connection.getInputStream();
   BufferedReader breader = new BufferedReader(
     new InputStreamReader(in, "utf-8"));
        
   String currentLine;
   while ((currentLine = breader.readLine()) != null) {
     htmlCode += currentLine + System.getProperty("line.separator");
   }

方式2:还记得上家公司老大经常说我们,”有现成的东西不用,在那瞎折腾“顿时想起spring提供了专门的模版引擎,就果断拿来用之,写了个小demo放到正式环境测试完全OK,果断替换之 主要代码如下 大家都懂得:

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
  <property name="resourceLoaderPath" value="/WEB-INF/"/>
  <property name="velocityProperties">
   <props>
    <prop key="velocimacro.library"></prop>
                <prop key="default.contentType">text/html; charset=utf-8</prop>
                <prop key="output.encoding">utf-8</prop>
                <prop key="input.encoding">utf-8</prop>    
   </props>
  </property>                
    </bean>
    <bean id="templateEngine" class="com.jia.schain.commons.util.TemplateEngine">
        <property name="velocityEngine" ref="velocityEngine"/>       
    </bean>

 

 

public class TemplateEngine {
 private VelocityEngine velocityEngine;

 public void setVelocityEngine(VelocityEngine velocityEngine) {
  this.velocityEngine = velocityEngine;
 }
 /**
  *
  * @param pathname  路径名
  * @param templatefile  模版文件名
  * @param model     模版数据
  * @return
  */
 public String build(String pathname, String templatefile, Map model){
  StringWriter writer = new StringWriter();
        try {
            VelocityEngineUtils.mergeTemplate(velocityEngine, templatefile, "UTF-8", model, writer);
        } catch (VelocityException e) {
            e.printStackTrace();
        }
        String htmlStr = writer.toString();
        FileUtils.write(pathname, htmlStr);
        try {
   writer.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return htmlStr;
 }
}

 

 

原创粉丝点击