静态页面生成那些事

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

最初使用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;
 }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值