java jsp转html_JSP页面转换为HTML页面,动态转静态

前台使用静态页面的好处:没有数据库的交互用户访问网页加载更快,相传搜索引擎会更容易抓取静态网页的内容,所以前台使用静态页面还是有必要的。

转化的流程:

后台servlet中取到需要转换的动态JSP页面的地址,在原位置生成一个相应的html文件。如:

test/index.jsp 这样的就可以生成一个 test/index.html文件。

接下来看具体的代码实现过程:

1.一个根据JSP文件的具体地址取得具体代码的方法,此方法是可以重复使用的,所以我们可以将它封装为到工具类里下次直接使用,具体代码如下:

public static String getCode(String httpUrl ){ //参数是一个具体的http服务器的地址

String code="";//定义返回的具体代码

try{

InputStream in;

URL url = new UTL(httpUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestProperty("User-Agent", "Mozilla/4.0");

connection.connect();

in = connection.getInputStream();

InputStreamReader inputStreamReader = new InputStreamReader(in, "GBK");

BufferedReader reader = new BufferedReader(inputStreamReader);

String currentLine = "";

while((currentLine = reader.readLine()) != null ){

htmlCode += currentLine + "\n";

}catch{

reader.close();

inputStreamReader.close();

in.close();

}

return htmlCode;

}

2.以上代码实现了读取JSP文件内容并取到代码的过程,接下来要做的是将这些代码写入到一个HTML文件里,请开下面的具体方法:

public static synchronized void writeHtml(String filePath,String info){

PrintWriter writer = null;

try {

File file = new File(filePath);

boolean isExist = file.exists();

if(isExist != true){

file.createNewFile();

}else{

if(!flag.equals("NO")){

file.delete();

file.createNewFile();

}

}

writer = new PrintWriter(new FileOutputStream(file, true));

writer.print(info);

writer.close();

} catch (Exception e) {

e.printStackTrace();

}finally{

writer.close();

}

}

3.以上两个方法都会在servlet中调用,具体参数的值会在下面说到,下面是servlet中的具体代码:

protected void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{

request.setCharacterEncoding("GBK");

response.setCharacterEncoding("GBK");

response.setContentType("text/html,charset=GBK");

try {

String s = request.getRequestURL().toString();

String url = "";

String filePath = "";

url=s.substring(0, s.indexOf("/servlet"))+"/index.jsp";//index.jsp 是需要转变为静态页面的地址

String path = request.getSession().getServletContext().getRealPath("/");

filePath = path+"index.html";//生成html文件的绝对路径

String info=StringUtils.getHtmlCode(url);

StringUtils.writeHtml(filePath, info);

} catch (Exception e) {

e.printStackTrace();

}

}

以上代码就简单的实现了JSP转换为HTML的过程。其中的两个方法也可以写为一个方法。水平有限,请指正!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值