相信在互聯網企業或多或少都有一些需要生成靜態頁面的需求,下面就來談談我在項目裏面遇到的生成靜態頁面的問題:
最初使用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;
}
}