第七章 过滤器 Filter(二)

一  过滤器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()方法。

 package com.cy.wrapper;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; public class ReqWrapper extends HttpServletRequestWrapper{ public ReqWrapper(HttpServletRequest request) {
super(request);
} @Override
public String getHeader(String name) {
if("If-Modified-Since".equalsIgnoreCase(name)){
return null;
}else{
return super.getHeader(name);
}
} }

HttpServletResponseWrapper

 package com.cy.wrapper;

 import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper; public class RespWrapper extends HttpServletResponseWrapper{
//创建一个缓存字节流对象,用于缓存servlet写入的数据
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//创建一个自定义的字节输出流对象,提供给servlet调用。以便把数据写入缓存流对象
MyOutputStream mos = new MyOutputStream(baos);
//创建一个自定义的字符输出流对象,提供给servlet调用。以便把数据写入缓存流对象
PrintWriter pw = new PrintWriter(baos); public RespWrapper(HttpServletResponse response) {
super(response);
} @Override
public ServletOutputStream getOutputStream() throws IOException {
return mos;
} @Override
public PrintWriter getWriter() throws IOException {
return pw;
} /**
* 自定义一个ServletOutputStream的子类用于保存servlet端写入字节流数据
* @author hellokitty燕
*
*/
private static class MyOutputStream extends ServletOutputStream{
private ByteArrayOutputStream baos ; public MyOutputStream(ByteArrayOutputStream baos){
this.baos = baos;
}
@Override
public void write(int b) throws IOException {
baos.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
baos.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
baos.write(b);
} } //将缓存流中的数据以String方式返回
public String toString(){
return baos.toString();
}
//将缓存流中的数据以字节数组方式返回
public byte[] toByteArray(){
return baos.toByteArray();
} }

将文本格式转化成所需的html格式

 package com.cy.filter;

 import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date; 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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.cy.wrapper.ReqWrapper;
import com.cy.wrapper.RespWrapper; public class TextFilter implements Filter{ @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException { ReqWrapper req = new ReqWrapper((HttpServletRequest)arg0);
RespWrapper resp = new RespWrapper((HttpServletResponse)arg1); arg2.doFilter(req, resp);
arg1.setContentType("text/html;charset=utf-8");
PrintWriter pw = arg1.getWriter();
pw.print("<html>");
pw.print("<head>");
pw.print("</head>");
pw.print("<body style='background-color:green'>");
pw.print("<pre>");
pw.print("============== date:"+new Date().toString()+"===================<br/><br/>");
pw.print(resp.toString());
pw.print("<br/><br/>==========================================================");
pw.print("</pre>");
pw.print("</body>");
pw.print("</html>");
pw.close(); } @Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub } }

Servlet

 package com.cy.servlet;

 import java.io.FileInputStream;
import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class TextServlet extends HttpServlet{ @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取刚才覆盖以后的字节数出流。
ServletOutputStream sos = resp.getOutputStream();
String uri = req.getRequestURI();
String name = uri.substring(uri.lastIndexOf("/")+1);
String path = "/text/"+name;
//将相对路径转换为物理路径
path = getServletContext().getRealPath(path);
FileInputStream fis = new FileInputStream(path);
byte[] b = new byte[100];
int length = 0;
while(-1!=(length = fis.read(b, 0, 100))){
sos.write(b, 0, length);
}
sos.close();
fis.close();
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
} }

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>Filter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>s_text</servlet-name>
<servlet-class>com.cy.servlet.TextServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>s_text</servlet-name>
<url-pattern>*.txt</url-pattern>
</servlet-mapping> <filter>
<filter-name>text</filter-name>
<filter-class>com.cy.filter.TextFilter</filter-class>
</filter> <filter-mapping>
<filter-name>text</filter-name>
<url-pattern>*.txt</url-pattern>
</filter-mapping> </web-app>

 应用HttpServletResponseWrapper对象,压缩内容。

 package com.cy.wrapper;

 import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper; public class RespGzipWrapper extends HttpServletResponseWrapper { public MyOutputStream mos=new MyOutputStream();
public RespGzipWrapper(HttpServletResponse response) {
super(response);
} @Override
public ServletOutputStream getOutputStream() throws IOException {
return mos;
} public class MyOutputStream extends ServletOutputStream{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
@Override
public void write(int b) throws IOException {
baos.write(b);
}
@Override
public void write(byte[] b) throws IOException {
baos.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
baos.write(b, off, len);
} public String toString(String encode){
try {
return baos.toString(encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null; } } }

filter

 package com.cy.filter;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader; 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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.cy.wrapper.RespGzipWrapper; public class GzipFilter implements Filter{ @Override
public void destroy() { } @Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)arg0;
String uri=req.getRequestURI();
//获取读取文件后缀名
String exName=uri.substring(uri.lastIndexOf("."));
RespGzipWrapper rgw=new RespGzipWrapper((HttpServletResponse)arg1);
//调用后面的资源
arg2.doFilter(arg0, rgw);
//用返回的字符串创建字符读取流
StringReader sr=new StringReader(rgw.mos.toString("utf-8"));
//根据上面读取的流创建缓存读取流
BufferedReader br=new BufferedReader(sr);
String line="";
//创建压缩后的文件缓存区
StringBuffer sb=new StringBuffer();
while((line=br.readLine())!=null){
//追加到缓存区
sb.append(line.trim());
}
//设置压缩后的文件大小
arg1.setContentLength(sb.toString().getBytes("iso-8859-1").length);
//根据请求后缀名来设置请求头
if(".html".equals(exName)){
arg1.setContentType("text/html;charset="+rgw.getCharacterEncoding());
}else if(".js".equals(exName)){
arg1.setContentType("text/javascript;charset="+rgw.getCharacterEncoding());
}else if(".css".equals(exName)){
arg1.setContentType("text/css;charset="+rgw.getCharacterEncoding());
}
//响应到客户端浏览器
arg1.getWriter().print(sb.toString());
arg1.getWriter().close();
} @Override
public void init(FilterConfig arg0) throws ServletException { } }

html;

 <!DOCTYPE html>
<html>
<head>
<title>index.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/index.css">
<script type="text/javascript" src="../js/index.js"></script> </head> <body>
This is my HTML page! <br>
</body>
</html>

css:

 *{

     margin:;
padding:;
color:red;
}

js

window.onload=function(){ alert("hello"); };

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>GZIP</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <filter>
<filter-name>GzipFilter</filter-name>
<filter-class>com.cy.filter.GzipFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

最终结果:

第七章  过滤器 Filter(二)。。。。

第七章  过滤器 Filter(二)

第七章  过滤器 Filter(二)

上一篇:MyEclipse 常用设置


下一篇:终于找到一款像样的saas门店收银系统源码了