过滤器为JSP文件生成静态页面

时间:2024-04-12 10:34:30

用过滤器为JSP文件生成静态页面,这只是一个简单的实例,客户端浏览器第一次请求JSP页面时,服务器将生成对应的HTML文件,以后访问同一JSP文件,将转为访问生成的HTML文件。
一、过滤器

package com.kenfor.lyb.toHtmlfilter;
import java.io.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.*;
public class JspFilter implements Filter { Logger logger = Logger.getLogger(this.getClass()); protected FilterConfig config;
public void init(FilterConfig config)
throws ServletException
{
// Save the config object
this.config = config;
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest hreq = (HttpServletRequest) request;
HttpServletResponse hresp = (HttpServletResponse) response;
String name = hreq.getRequestURL().substring(hreq.getRequestURL().lastIndexOf("/") + 1,
hreq.getRequestURL().lastIndexOf("."));
//logger.info("fileName="+name);
String str_uri = hreq.getRequestURI();
//logger.info("str_uri="+str_uri);
String htmpath=hreq.getSession().getServletContext().getRealPath(
"/")
+ "HTML\\"
+ str_uri.substring(0, str_uri.lastIndexOf("/"))
//+"/"+time
+ "/" + name + ".html";
File file = new File(htmpath);
//logger.info("file="+file);
String to=hreq.getContextPath() + "/HTML"
+ str_uri.substring(0, str_uri.lastIndexOf("/"))
+"/"+ name + ".html";
//logger.info(to); if (!file.exists()&&hreq.getRequestURL().indexOf(".jsp")> 0) {
ServletResponse newResponse =new CharResponseWrapper(hresp);
chain.doFilter(request, newResponse);
String text = newResponse.toString();
if (text != null)
{
PrintWriter pw=new PrintWriter(htmpath);
pw.println(text);
pw.close();
hresp.sendRedirect(to);
}
} else { hresp.sendRedirect(to);
} } }

二、响应包装器

package com.kenfor.lyb.toHtmlfilter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
/**
* Simple response wrapper that utilizes a local CharArrayWriter
* for output
*/
public class CharResponseWrapper
extends HttpServletResponseWrapper
{
protected CharArrayWriter charWriter;
protected PrintWriter writer;
protected boolean getOutputStreamCalled;
protected boolean getWriterCalled;
public CharResponseWrapper(HttpServletResponse response)
{
super(response);
// Create the writer
charWriter = new CharArrayWriter();
}
public ServletOutputStream getOutputStream()
throws IOException
{
// Can't call getOutputStream if getWriter
// has already been called
if (getWriterCalled)
{
throw new IllegalStateException(
"getWriter already called");
}
getOutputStreamCalled = true;
return super.getOutputStream();
}
public PrintWriter getWriter()
throws IOException
{
if (writer != null)
{
return writer;
}
// Can't call getWriter if getOutputStream
// has already been called
if (getOutputStreamCalled)
{
throw new IllegalStateException(
"getOutputStream already called");
}
getWriterCalled = true;
writer = new PrintWriter(charWriter);
return writer;
}
public String toString()
{
String s = null;
// Only return a String if the writer was
// used.
if (writer != null)
{
s = charWriter.toString();
}
return s;
}
public char[] toCharArray(){//将响应数据以字符数组返回
return(charWriter.toCharArray());
} }

三、web.xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>

<filter>
  <filter-name>jspfilter</filter-name>
  <filter-class>com.kenfor.lyb.toHtmlfilter.JspFilter</filter-class>
</filter>

<filter-mapping> 
  <filter-name>jspfilter</filter-name>
  <url-pattern>*.jsp</url-pattern>
</filter-mapping>

<servlet> 
  <servlet-name>log4j-init</servlet-name> 
  <servlet-class>example.Log4jInit</servlet-class> 
  <init-param> 
   <param-name>log4j</param-name> 
   <param-value>WEB-INF/log4j.properties</param-value> 
  </init-param> 
 <load-on-startup>1</load-on-startup> 
</servlet> 
</web-app>

测试文件:tohtml.jsp

<%@ page contentType="text/html; charset=gb2312" %>
<%
String name = request.getRequestURL().substring(request.getRequestURL().lastIndexOf("/") + 1,
request.getRequestURL().lastIndexOf("."));
String cox=request.getContextPath();

String str_uri = request.getRequestURI();
out.println(request.getRequestURL()+"<br>");
out.println(name+"<br>");
out.println(str_uri+"<br>");
out.println(cox+"<br>");
out.println(request.getParameter("type")); 
%>

第二次请求tohtml.jsp时,运行图:

过滤器为JSP文件生成静态页面