使用jsp生成静态页面.整个工程的目录结构如图:
StaticPage是我们将要生成的静态页面目录 所有静态页面都会生成在这个目录.
然后编写一个MyFitler的过滤器:
以下是代码片段:
package com.filter;
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.*;
public class MyFilter implements Filter { private FilterConfig filterConfig;
public void destroy() {
}
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
String para = arg0.getParameter("id"); if (para != null) { // 获得静态文件生成的绝对地址 para = arg0.getRealPath("/") + "StaticPage/" + para + ".html"; File file = new File(para);
// 判断文件是否存在 if (!file.exists()) {// 不存在 生成 FileWriter fileWriter = new FileWriter(file); StringBuilder sb = new StringBuilder(1000); sb.append("这个页面是静态页面 " + para + " "); sb.append("当前时间:" + new java.util.Date().toLocaleString() + " "); sb .append("<a> back</a>"); fileWriter.write(sb.toString()); fileWriter.flush(); fileWriter.close(); } // 转向到该html页面 HttpServletResponse hsr = (HttpServletResponse) arg1; hsr.sendRedirect("/BuildeStatic/StaticPage/" + arg0.getParameter("id") + ".html"); return; } arg2.doFilter(arg0, arg1); }
public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub this.filterConfig = filterConfig; }
}
然后配置web.xml使上面的过滤器针对StaticPage目录生效:
然后编写StaticPage下的index.jsp文件 作为目录页面
以下是代码片段: <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>">
<title>index</title>
<meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body> <a href="/BuildeStatic/StaticPage/index.jsp?id=123">1号静态页面</a> <br> <a href="/BuildeStatic/StaticPage/index.jsp?id=124">2号静态页面</a> <br> <a href="/BuildeStatic/StaticPage/index.jsp?id=125">3号静态页面</a> <br> <a href="/BuildeStatic/StaticPage/index.jsp?id=126">4号静态页面</a> <br> </body> </html>