一 过滤器API
由容器实现的接口
–javax.servlet.Filter
–javax.servlet.FilterChain
–javax.servlet.FilterConfig
四个包装器类
–javax.servlet.ServletRequestWrapper
–javax.servlet.ServletResponseWrapper
–javax.servlet.http.HttpServletRequestWrapper
–javax.servlet.http.HttpServletResponseWrapper
二 使用请求和响应包装器
示例:
假如我们有个老系统用来产生普通的ASCII文本格式的报表,并将报表保存在扩展名为.txt的文本文件中。现在我们想让这些报表可以通过浏览器访问。我们把文件保存在/text/a.txt。
如果 If-Modified-Since 值指定的时间内容资源没有更改过,那么服务器就不需要发送资源。
将请求包装在 HttpServletRequestWrapper 中 并覆盖 getHeader()方法。
1 package com.cy.wrapper; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletRequestWrapper; 5 6 public class ReqWrapper extends HttpServletRequestWrapper{ 7 8 public ReqWrapper(HttpServletRequest request) { 9 super(request); 10 } 11 12 @Override 13 public String getHeader(String name) { 14 if("If-Modified-Since".equalsIgnoreCase(name)){ 15 return null; 16 }else{ 17 return super.getHeader(name); 18 } 19 } 20 21 22 23 }
HttpServletResponseWrapper
1 package com.cy.wrapper; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 7 import javax.servlet.ServletOutputStream; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpServletResponseWrapper; 10 11 public class RespWrapper extends HttpServletResponseWrapper{ 12 //创建一个缓存字节流对象,用于缓存servlet写入的数据 13 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 14 //创建一个自定义的字节输出流对象,提供给servlet调用。以便把数据写入缓存流对象 15 MyOutputStream mos = new MyOutputStream(baos); 16 //创建一个自定义的字符输出流对象,提供给servlet调用。以便把数据写入缓存流对象 17 PrintWriter pw = new PrintWriter(baos); 18 19 20 public RespWrapper(HttpServletResponse response) { 21 super(response); 22 } 23 24 @Override 25 public ServletOutputStream getOutputStream() throws IOException { 26 return mos; 27 } 28 29 @Override 30 public PrintWriter getWriter() throws IOException { 31 return pw; 32 } 33 34 35 /** 36 * 自定义一个ServletOutputStream的子类用于保存servlet端写入字节流数据 37 * @author hellokitty燕 38 * 39 */ 40 private static class MyOutputStream extends ServletOutputStream{ 41 private ByteArrayOutputStream baos ; 42 43 public MyOutputStream(ByteArrayOutputStream baos){ 44 this.baos = baos; 45 } 46 @Override 47 public void write(int b) throws IOException { 48 baos.write(b); 49 } 50 @Override 51 public void write(byte[] b, int off, int len) throws IOException { 52 baos.write(b, off, len); 53 } 54 @Override 55 public void write(byte[] b) throws IOException { 56 baos.write(b); 57 } 58 59 } 60 61 //将缓存流中的数据以String方式返回 62 public String toString(){ 63 return baos.toString(); 64 } 65 //将缓存流中的数据以字节数组方式返回 66 public byte[] toByteArray(){ 67 return baos.toByteArray(); 68 } 69 70 71 72 }
将文本格式转化成所需的html格式
1 package com.cy.filter; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.Date; 6 7 import javax.servlet.Filter; 8 import javax.servlet.FilterChain; 9 import javax.servlet.FilterConfig; 10 import javax.servlet.ServletException; 11 import javax.servlet.ServletRequest; 12 import javax.servlet.ServletResponse; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 import com.cy.wrapper.ReqWrapper; 17 import com.cy.wrapper.RespWrapper; 18 19 public class TextFilter implements Filter{ 20 21 @Override 22 public void destroy() { 23 // TODO Auto-generated method stub 24 25 } 26 27 @Override 28 public void doFilter(ServletRequest arg0, ServletResponse arg1, 29 FilterChain arg2) throws IOException, ServletException { 30 31 ReqWrapper req = new ReqWrapper((HttpServletRequest)arg0); 32 RespWrapper resp = new RespWrapper((HttpServletResponse)arg1); 33 34 arg2.doFilter(req, resp); 35 arg1.setContentType("text/html;charset=utf-8"); 36 PrintWriter pw = arg1.getWriter(); 37 pw.print("<html>"); 38 pw.print("<head>"); 39 pw.print("</head>"); 40 pw.print("<body style='background-color:green'>"); 41 pw.print("<pre>"); 42 pw.print("============== date:"+new Date().toString()+"===================<br/><br/>"); 43 pw.print(resp.toString()); 44 pw.print("<br/><br/>=========================================================="); 45 pw.print("</pre>"); 46 pw.print("</body>"); 47 pw.print("</html>"); 48 pw.close(); 49 50 51 } 52 53 @Override 54 public void init(FilterConfig arg0) throws ServletException { 55 // TODO Auto-generated method stub 56 57 } 58 59 }
Servlet
1 package com.cy.servlet; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.ServletOutputStream; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 public class TextServlet extends HttpServlet{ 13 14 @Override 15 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 16 throws ServletException, IOException { 17 //获取刚才覆盖以后的字节数出流。 18 ServletOutputStream sos = resp.getOutputStream(); 19 String uri = req.getRequestURI(); 20 String name = uri.substring(uri.lastIndexOf("/")+1); 21 String path = "/text/"+name; 22 //将相对路径转换为物理路径 23 path = getServletContext().getRealPath(path); 24 FileInputStream fis = new FileInputStream(path); 25 byte[] b = new byte[100]; 26 int length = 0; 27 while(-1!=(length = fis.read(b, 0, 100))){ 28 sos.write(b, 0, length); 29 } 30 sos.close(); 31 fis.close(); 32 } 33 34 @Override 35 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 36 throws ServletException, IOException { 37 doGet(req, resp); 38 } 39 40 }
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>Filter</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 14 15 <servlet> 16 <servlet-name>s_text</servlet-name> 17 <servlet-class>com.cy.servlet.TextServlet</servlet-class> 18 </servlet> 19 20 <servlet-mapping> 21 <servlet-name>s_text</servlet-name> 22 <url-pattern>*.txt</url-pattern> 23 </servlet-mapping> 24 25 <filter> 26 <filter-name>text</filter-name> 27 <filter-class>com.cy.filter.TextFilter</filter-class> 28 </filter> 29 30 <filter-mapping> 31 <filter-name>text</filter-name> 32 <url-pattern>*.txt</url-pattern> 33 </filter-mapping> 34 35 36 </web-app>
应用HttpServletResponseWrapper对象,压缩内容。
1 package com.cy.wrapper; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.UnsupportedEncodingException; 6 7 import javax.servlet.ServletOutputStream; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpServletResponseWrapper; 10 11 public class RespGzipWrapper extends HttpServletResponseWrapper { 12 13 public MyOutputStream mos=new MyOutputStream(); 14 public RespGzipWrapper(HttpServletResponse response) { 15 super(response); 16 } 17 18 @Override 19 public ServletOutputStream getOutputStream() throws IOException { 20 return mos; 21 } 22 23 24 public class MyOutputStream extends ServletOutputStream{ 25 ByteArrayOutputStream baos=new ByteArrayOutputStream(); 26 @Override 27 public void write(int b) throws IOException { 28 baos.write(b); 29 } 30 @Override 31 public void write(byte[] b) throws IOException { 32 baos.write(b); 33 } 34 @Override 35 public void write(byte[] b, int off, int len) throws IOException { 36 baos.write(b, off, len); 37 } 38 39 public String toString(String encode){ 40 try { 41 return baos.toString(encode); 42 } catch (UnsupportedEncodingException e) { 43 e.printStackTrace(); 44 } 45 return null; 46 47 } 48 49 } 50 51 52 }
filter
1 package com.cy.filter; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.StringReader; 6 7 import javax.servlet.Filter; 8 import javax.servlet.FilterChain; 9 import javax.servlet.FilterConfig; 10 import javax.servlet.ServletException; 11 import javax.servlet.ServletRequest; 12 import javax.servlet.ServletResponse; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 import com.cy.wrapper.RespGzipWrapper; 17 18 public class GzipFilter implements Filter{ 19 20 @Override 21 public void destroy() { 22 23 } 24 25 @Override 26 public void doFilter(ServletRequest arg0, ServletResponse arg1, 27 FilterChain arg2) throws IOException, ServletException { 28 HttpServletRequest req=(HttpServletRequest)arg0; 29 String uri=req.getRequestURI(); 30 //获取读取文件后缀名 31 String exName=uri.substring(uri.lastIndexOf(".")); 32 RespGzipWrapper rgw=new RespGzipWrapper((HttpServletResponse)arg1); 33 //调用后面的资源 34 arg2.doFilter(arg0, rgw); 35 //用返回的字符串创建字符读取流 36 StringReader sr=new StringReader(rgw.mos.toString("utf-8")); 37 //根据上面读取的流创建缓存读取流 38 BufferedReader br=new BufferedReader(sr); 39 String line=""; 40 //创建压缩后的文件缓存区 41 StringBuffer sb=new StringBuffer(); 42 while((line=br.readLine())!=null){ 43 //追加到缓存区 44 sb.append(line.trim()); 45 } 46 //设置压缩后的文件大小 47 arg1.setContentLength(sb.toString().getBytes("iso-8859-1").length); 48 //根据请求后缀名来设置请求头 49 if(".html".equals(exName)){ 50 arg1.setContentType("text/html;charset="+rgw.getCharacterEncoding()); 51 }else if(".js".equals(exName)){ 52 arg1.setContentType("text/javascript;charset="+rgw.getCharacterEncoding()); 53 }else if(".css".equals(exName)){ 54 arg1.setContentType("text/css;charset="+rgw.getCharacterEncoding()); 55 } 56 //响应到客户端浏览器 57 arg1.getWriter().print(sb.toString()); 58 arg1.getWriter().close(); 59 } 60 61 @Override 62 public void init(FilterConfig arg0) throws ServletException { 63 64 } 65 66 }
html;
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>index.html</title> 5 6 <meta name="keywords" content="keyword1,keyword2,keyword3"> 7 <meta name="description" content="this is my page"> 8 <meta name="content-type" content="text/html; charset=UTF-8"> 9 10 <link rel="stylesheet" type="text/css" href="../css/index.css"> 11 <script type="text/javascript" src="../js/index.js"></script> 12 13 </head> 14 15 <body> 16 This is my HTML page! <br> 17 </body> 18 </html>
css:
1 *{ 2 3 margin: 0; 4 padding: 0; 5 color:red; 6 }
js
1 window.onload=function(){ 2 alert("hello"); 3 };
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>GZIP</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 <filter> 14 <filter-name>GzipFilter</filter-name> 15 <filter-class>com.cy.filter.GzipFilter</filter-class> 16 </filter> 17 <filter-mapping> 18 <filter-name>GzipFilter</filter-name> 19 <url-pattern>/*</url-pattern> 20 </filter-mapping> 21 </web-app>
最终结果:
。。。。