使用Web过滤器实现:将原始页面的内容修改后返回给客户端
①index.jsp(使用入门1教程中的页面,无改动,任一一个JSP页面都可以)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <%-- 这里的action使用的是相对路径,代表进入该路径--%> <form action="Login" method="post"> 用户:<input type="text" name="username"> 密码:<input type="password" name="userpwd"> <input type="submit" value="登录"> </form> </body> </html>
②继承了HttpServletResponseWrapper响应包装类的Java类:
public class HttpResponseWrapper extends HttpServletResponseWrapper { // CharArrayWriter对象包含了返回的原始页面内容 private CharArrayWriter caw; // PrintWriter对象可以动态产生页面,使用它可以向客户发送文本数据 private PrintWriter pw; // 创建了一个构造方法与父类匹配 public HttpResponseWrapper(HttpServletResponse response) { super(response); caw = new CharArrayWriter(); pw = new PrintWriter(caw); } public String getResponseString() { // 返回原始的页面内容 return caw.toString(); } // 重写了getWriter()方法,调用响应对象的getWriter()方法返回PrintWriter类的对象 public PrintWriter getWriter() { return pw; } }
③实现了Filter接口的过滤器类(拦截响应并修改页面内容)
public class TrimFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpResponseWrapper responseWrapper = new HttpResponseWrapper((HttpServletResponse)resp); chain.doFilter(req, responseWrapper); //返回到过滤器时,截获页面返回的内容,修改HTML代码后再返回给客户端 String trimHtml = responseWrapper.getResponseString().replaceAll("[\t\r\n]",""); // 必须使用response对象的getWriter()方法获取到PrintWriter对象输出页面内容 resp.getWriter().print(trimHtml); } public void init(FilterConfig config) throws ServletException { } }
④在Web.xml中配置该过滤器:
<filter> <filter-name>TrimFilter</filter-name> <filter-class>cn.qi.filter.TrimFilter</filter-class> </filter> <filter-mapping> <filter-name>TrimFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>