标签:
在filter中可以得到代表用户请求和响应的request、response对象,因此在编程中可以使用Decorator(装饰器)模式对request、response对象进行包装,再把包装对象传给目标资源,从而实现一些特殊需求。
当某个对象的方法不适应业务需求时,通常有2种方式可以对方法进行增强:
在阎宏博士的《JAVA与模式》一书中开头是这样描述装饰(Decorator)模式的:装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
那么在实际应用中遇到需增强对象的方法时,到底选用哪种方式比较好呢?这个没有具体的定式,只能是根据具体的需求来采用具体的方式,不过有一种情况下,必须使用Decorator设计模式:即被增强的对象,开发人员只能得到它的对象,无法得到它的class文件。比如request、response对象,开发人员之所以在servlet中能通过sun公司定义的HttpServletRequest\response接口去操作这些对象,是因为Tomcat服务器厂商编写了request、response接口的实现类。web服务器在调用servlet时,会用这些接口的实现类创建出对象,然后传递给servlet程序。此种情况下,由于开发人员根本不知道服务器厂商编写的request、response接口的实现类是哪个?在程序中只能拿到服务器厂商提供的对象,因此就只能采用Decorator设计模式对这些对象进行增强。
1.首先看需要被增强对象继承了什么接口或父类,编写一个类也去继承这些接口或父类。
2.在类中定义一个变量,变量类型即需增强对象的类型。
3.在类中定义一个构造函数,接收需增强的对象。
4.覆盖需增强的方法,编写增强的代码。
Servlet API 中提供了一个request对象的Decorator设计模式的默认实现类HttpServletRequestWrapper,HttpServletRequestWrapper 类实现了request 接口中的所有方法,但这些方法的内部实现都是仅仅调用了一下所包装的的 request 对象的对应方法,以避免用户在对request对象进行增强时需要实现request接口中的所有方法。
编写一个用于处理中文乱码的过滤器CharacterEncodingFilter,代码如下:
1 2 public class CharacterEncodingFilter implements Filter { 3 4 private FilterConfig filterConfig = null; 5 //设置默认的字符编码 6 private String defaultCharset = "UTF-8"; 7 8 public void doFilter(ServletRequest req, ServletResponse resp, 9 FilterChain chain) throws IOException, ServletException { 10 11 HttpServletRequest request = (HttpServletRequest) req; 12 HttpServletResponse response = (HttpServletResponse) resp; 13 //得到在web.xml中配置的字符编码 14 String charset = filterConfig.getInitParameter("charset"); 15 if(charset==null){ 16 charset = defaultCharset; 17 } 18 request.setCharacterEncoding(charset); 19 response.setCharacterEncoding(charset); 20 response.setContentType("text/html;charset="+charset); 21 22 MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request); 23 chain.doFilter(requestWrapper, response); 24 } 25 26 public void init(FilterConfig filterConfig) throws ServletException { 27 //得到过滤器的初始化配置信息 28 this.filterConfig = filterConfig; 29 } 30 31 public void destroy() { 32 33 } 34 } 35 36 /** 37 * @Description: Servlet API中提供了一个request对象的Decorator设计模式的默认实现类HttpServletRequestWrapper, 38 * (HttpServletRequestWrapper类实现了request接口中的所有方法,但这些方法的内部实现都是仅仅调用了一下所包装的的 request对象的对应方法) 39 * 以避免用户在对request对象进行增强时需要实现request接口中的所有方法。 40 * 所以当需要增强request对象时,只需要写一个类继承HttpServletRequestWrapper类,然后在重写需要增强的方法即可 41 * 1.实现与被增强对象相同的接口 42 2、定义一个变量记住被增强对象 43 3、定义一个构造函数,接收被增强对象 44 4、覆盖需要增强的方法 45 5、对于不想增强的方法,直接调用被增强对象(目标对象)的方法 46 */ 47 class MyCharacterEncodingRequest extends HttpServletRequestWrapper{ 48 //定义一个变量记住被增强对象(request对象是需要被增强的对象) 49 private HttpServletRequest request; 50 //定义一个构造函数,接收被增强对象 51 public MyCharacterEncodingRequest(HttpServletRequest request) { 52 super(request); 53 this.request = request; 54 } 55 /* 覆盖需要增强的getParameter方法 56 * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) 57 */ 58 @Override 59 public String getParameter(String name) { 60 try{ 61 //获取参数的值 62 String value= this.request.getParameter(name); 63 if(value==null){ 64 return null; 65 } 66 //如果不是以get方式提交数据的,就直接返回获取到的值 67 if(!this.request.getMethod().equalsIgnoreCase("get")) { 68 return value; 69 }else{ 70 //如果是以get方式提交数据的,就对获取到的值进行转码处理 71 value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding()); 72 return value; 73 } 74 }catch (Exception e) { 75 throw new RuntimeException(e); 76 } 77 } 78 }
在web.xml文件中配置CharacterEncodingFilter:
1 <!--配置字符过滤器,解决get、post请求方式下的中文乱码问题--> 2 <filter> 3 <filter-name>CharacterEncodingFilter</filter-name> 4 <filter-class>me.gacl.web.filter.CharacterEncodingFilter</filter-class> 5 </filter> 6 7 <filter-mapping> 8 <filter-name>CharacterEncodingFilter</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping>
编写jsp测试页面,如下:
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 <%--引入jstl标签库 --%> 3 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 4 <!DOCTYPE HTML> 5 <html> 6 <head> 7 <title>使用字符过滤器解决解决get、post请求方式下的中文乱码问题</title> 8 </head> 9 10 <body> 11 <%--使用c:url标签构建url,构建好的url存储在servletDemo1变量中--%> 12 <c:url value="/servlet/ServletDemo1" scope="page" var="servletDemo1"> 13 <%--构建的url的附带的中文参数 ,参数名是:username,值是:孤傲苍狼--%> 14 <c:param name="username" value="孤傲苍狼"></c:param> 15 </c:url> 16 <%--使用get的方式访问 --%> 17 <a href="${servletDemo1}">超链接(get方式请求)</a> 18 <hr/> 19 <%--使用post方式提交表单 --%> 20 <form action="${pageContext.request.contextPath}/servlet/ServletDemo1" method="post"> 21 用户名:<input type="text" name="username" value="孤傲苍狼" /> 22 <input type="submit" value="post方式提交"> 23 </form> 24 25 </body> 26 </html>
编写处理用户请求的ServletDemo1
1 class ServletDemo1 extends HttpServlet { 2 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 //接收参数 6 String username = request.getParameter("username"); 7 //获取请求方式 8 String method = request.getMethod(); 9 //获取输出流 10 PrintWriter out = response.getWriter(); 11 out.write("请求的方式:"+method); 12 out.write("<br/>"); 13 out.write("接收到的参数:"+username); 14 } 15 16 public void doPost(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException { 18 doGet(request, response); 19 } 20 21 }
这样, 无论是get请求方式还是post请求方式,中文乱码问题都可以完美解决了。
编写一个html转义过滤器,代码如下:
1 public class HtmlFilter implements Filter { 2 3 public void doFilter(ServletRequest req, ServletResponse resp, 4 FilterChain chain) throws IOException, ServletException { 5 6 HttpServletRequest request = (HttpServletRequest) req; 7 HttpServletResponse response = (HttpServletResponse) resp; 8 9 MyHtmlRequest myrequest = new MyHtmlRequest(request); 10 chain.doFilter(myrequest, response); 11 12 } 13 14 15 public void destroy() { 16 17 } 18 19 20 public void init(FilterConfig filterConfig) throws ServletException { 21 22 } 23 } 24 25 class MyHtmlRequest extends HttpServletRequestWrapper { 26 27 private HttpServletRequest request; 28 29 public MyHtmlRequest(HttpServletRequest request) { 30 super(request); 31 this.request = request; 32 } 33 34 /* 覆盖需要增强的getParameter方法 35 * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) 36 */ 37 @Override 38 public String getParameter(String name) { 39 String value = this.request.getParameter(name); 40 if (value == null) { 41 return null; 42 } 43 //调用filter转义value中的html标签 44 return filter(value); 45 } 46 47 public String filter(String message) { 48 if (message == null){ 49 return null; 50 } 51 char content[] = new char[message.length()]; 52 message.getChars(0, message.length(), content, 0); 53 StringBuffer result = new StringBuffer(content.length + 50); 54 for (int i = 0; i < content.length; i++) { 55 switch (content[i]) { 56 case ‘<‘: 57 result.append("<"); 58 break; 59 case ‘>‘: 60 result.append(">"); 61 break; 62 case ‘&‘: 63 result.append("&"); 64 break; 65 case ‘"‘: 66 result.append("""); 67 break; 68 default: 69 result.append(content[i]); 70 } 71 } 72 return result.toString(); 73 } 74 }
在web.xml文件中配置HtmlFilter
1 <!--配置Html过滤器,转义内容中的html标签--> 2 <filter> 3 <filter-name>HtmlFilter</filter-name> 4 <filter-class>me.gacl.web.filter.HtmlFilter</filter-class> 5 </filter> 6 7 <filter-mapping> 8 <filter-name>HtmlFilter</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping>
编写jsp测试页面,如下:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML> 3 <html> 4 <head> 5 <title>html过滤器测试</title> 6 </head> 7 8 <body> 9 <form action="${pageContext.request.contextPath}/servlet/ServletDemo2" method="post"> 10 留言: 11 <textarea rows="8" cols="70" name="message"> 12 <script type="text/javascript"> 13 while(true){ 14 alert("死循环了,我会不停地弹出了"); 15 } 16 </script> 17 <a href="http://www.cnblogs.com">访问博客园</a> 18 </textarea> 19 <input type="submit" value="发表"> 20 </form> 21 </body> 22 </html>
编写处理用户请求的ServletDemo2
1 public class ServletDemo2 extends HttpServlet { 2 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 //获取用户输入的内容 6 String message = request.getParameter("message"); 7 response.getWriter().write("您上次的留言是:<br/>" + message); 8 } 9 10 public void doPost(HttpServletRequest request, HttpServletResponse response) 11 throws ServletException, IOException { 12 doGet(request, response); 13 } 14 }
这样, 所有的html标签都被转义输出了。
编写一个敏感字符过滤器,代码如下:
1 public class DirtyFilter implements Filter { 2 3 private FilterConfig config = null; 4 5 @Override 6 public void init(FilterConfig filterConfig) throws ServletException { 7 this.config = filterConfig; 8 } 9 10 @Override 11 public void doFilter(ServletRequest req, ServletResponse resp, 12 FilterChain chain) throws IOException, ServletException { 13 14 HttpServletRequest request = (HttpServletRequest) req; 15 HttpServletResponse response = (HttpServletResponse) resp; 16 DirtyRequest dirtyrequest = new DirtyRequest(request); 17 18 chain.doFilter(dirtyrequest, response); 19 } 20 21 @Override 22 public void destroy() { 23 24 } 25 26 private List<String> getDirtyWords(){ 27 List<String> dirtyWords = new ArrayList<String>(); 28 String dirtyWordPath = config.getInitParameter("dirtyWord"); 29 InputStream inputStream = config.getServletContext().getResourceAsStream(dirtyWordPath); 30 InputStreamReader is = null; 31 try { 32 is = new InputStreamReader(inputStream,"UTF-8"); 33 } catch (UnsupportedEncodingException e2) { 34 e2.printStackTrace(); 35 } 36 BufferedReader reader = new BufferedReader(is); 37 String line; 38 try { 39 while ((line = reader.readLine())!= null) {//如果 line为空说明读完了 40 dirtyWords.add(line); 41 } 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } 45 return dirtyWords; 46 } 47 48 class DirtyRequest extends HttpServletRequestWrapper{ 49 50 private List<String> dirtyWords = getDirtyWords(); 51 private HttpServletRequest request; 52 public DirtyRequest(HttpServletRequest request) { 53 super(request); 54 this.request = request; 55 } 56 /* 重写getParameter方法,实现对敏感字符的过滤 57 * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) 58 */ 59 @Override 60 public String getParameter(String name) { 61 62 String value = this.request.getParameter(name); 63 if(value==null){ 64 return null; 65 } 66 67 for(String dirtyWord : dirtyWords){ 68 if(value.contains(dirtyWord)){ 69 System.out.println("内容中包含敏感词:"+dirtyWord+",将会被替换成****"); 70 //替换敏感字符 71 value = value.replace(dirtyWord, "****"); 72 } 73 } 74 return value; 75 } 76 } 77 }
在web.xml文件中配置DirtyFilter
1 <!--配置敏感字符过滤器--> 2 <filter> 3 <filter-name>DirtyFilter</filter-name> 4 <filter-class>me.gacl.web.filter.DirtyFilter</filter-class> 5 <!-- 配置要过滤的敏感字符文件 --> 6 <init-param> 7 <param-name>dirtyWord</param-name> 8 <param-value>/WEB-INF/DirtyWord.txt</param-value> 9 </init-param> 10 </filter> 11 12 <filter-mapping> 13 <filter-name>DirtyFilter</filter-name> 14 <url-pattern>/*</url-pattern> 15 </filter-mapping>
当用户填写的内容包含一些敏感字符时,在DirtyFilter过滤器中就会将这些敏感字符替换掉。
我们如果将上述的CharacterEncodingFilter、HtmlFilter、DirtyFilter这三个过滤器联合起来使用,那么就相当于是把request对象包装了3次,request对象的getParameter方法经过3次重写,使得getParameter方法的功能大大增强,可以同时解决中文乱码,html标签转义,敏感字符过滤这些需求。
在实际开发中完全可以将上述的三个过滤器合并成一个,让合并后的过滤器具有解决中文乱码,html标签转义,敏感字符过滤这些功能,例如:
1 public class AdvancedFilter implements Filter { 2 3 private FilterConfig filterConfig = null; 4 //设置默认的字符编码 5 private String defaultCharset = "UTF-8"; 6 7 @Override 8 public void init(FilterConfig filterConfig) throws ServletException { 9 //得到过滤器的初始化配置信息 10 this.filterConfig = filterConfig; 11 } 12 13 @Override 14 public void doFilter(ServletRequest req, ServletResponse resp, 15 FilterChain chain) throws IOException, ServletException { 16 HttpServletRequest request = (HttpServletRequest) req; 17 HttpServletResponse response = (HttpServletResponse) resp; 18 //得到在web.xml中配置的字符编码 19 String charset = filterConfig.getInitParameter("charset"); 20 if(charset==null){ 21 charset = defaultCharset; 22 } 23 request.setCharacterEncoding(charset); 24 response.setCharacterEncoding(charset); 25 response.setContentType("text/html;charset="+charset); 26 27 AdvancedRequest requestWrapper = new AdvancedRequest(request); 28 chain.doFilter(requestWrapper, response); 29 } 30 31 @Override 32 public void destroy() { 33 34 } 35 36 class AdvancedRequest extends HttpServletRequestWrapper{ 37 38 private List<String> dirtyWords = getDirtyWords(); 39 40 //定义一个变量记住被增强对象(request对象是需要被增强的对象) 41 private HttpServletRequest request; 42 //定义一个构造函数,接收被增强对象 43 public AdvancedRequest(HttpServletRequest request) { 44 super(request); 45 this.request = request; 46 } 47 /* 覆盖需要增强的getParameter方法 48 * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) 49 */ 50 @Override 51 public String getParameter(String name) { 52 try{ 53 //获取参数的值 54 String value= this.request.getParameter(name); 55 if(value==null){ 56 return null; 57 } 58 //如果不是以get方式提交数据的,就直接返回获取到的值 59 if(!this.request.getMethod().equalsIgnoreCase("get")) { 60 //调用filter转义value中的html标签 61 value= filter(value); 62 }else{ 63 //如果是以get方式提交数据的,就对获取到的值进行转码处理 64 value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding()); 65 //调用filter转义value中的html标签 66 value= filter(value); 67 } 68 69 for(String dirtyWord : dirtyWords){ 70 if(value.contains(dirtyWord)){ 71 System.out.println("内容中包含敏感词:"+dirtyWord+",将会被替换成****"); 72 //替换敏感字符 73 value = value.replace(dirtyWord, "****"); 74 } 75 } 76 return value; 77 }catch (Exception e) { 78 throw new RuntimeException(e); 79 } 80 } 81 } 82 83 public String filter(String value) { 84 if (value == null){ 85 return null; 86 } 87 char content[] = new char[value.length()]; 88 value.getChars(0, value.length(), content, 0); 89 StringBuffer result = new StringBuffer(content.length + 50); 90 for (int i = 0; i < content.length; i++) { 91 switch (content[i]) { 92 case ‘<‘: 93 result.append("<"); 94 break; 95 case ‘>‘: 96 result.append(">"); 97 break; 98 case ‘&‘: 99 result.append("&"); 100 break; 101 case ‘"‘: 102 result.append("""); 103 break; 104 default: 105 result.append(content[i]); 106 } 107 } 108 return (result.toString()); 109 } 110 111 private List<String> getDirtyWords(){ 112 List<String> dirtyWords = new ArrayList<String>(); 113 String dirtyWordPath = filterConfig.getInitParameter("dirtyWord"); 114 InputStream inputStream = filterConfig.getServletContext().getResourceAsStream(dirtyWordPath); 115 InputStreamReader is = null; 116 try { 117 is = new InputStreamReader(inputStream,defaultCharset); 118 } catch (UnsupportedEncodingException e2) { 119 e2.printStackTrace(); 120 } 121 BufferedReader reader = new BufferedReader(is); 122 String line; 123 try { 124 while ((line = reader.readLine())!= null) {//如果 line为空说明读完了 125 dirtyWords.add(line); 126 } 127 } catch (IOException e) { 128 e.printStackTrace(); 129 } 130 return dirtyWords; 131 } 132 }
在web.xml文件中配置AdvancedFilter
1 <filter> 2 <filter-name>AdvancedFilter</filter-name> 3 <filter-class>me.gacl.web.filter.AdvancedFilter</filter-class> 4 <init-param> 5 <param-name>charset</param-name> 6 <param-value>UTF-8</param-value> 7 </init-param> 8 <init-param> 9 <param-name>dirtyWord</param-name> 10 <param-value>/WEB-INF/DirtyWord.txt</param-value> 11 </init-param> 12 </filter> 13 14 <filter-mapping> 15 <filter-name>AdvancedFilter</filter-name> 16 <url-pattern>/*</url-pattern> 17 </filter-mapping>
AdvancedFilter过滤器同时具有解决中文乱码,转义内容中的html标签,过滤内容中的敏感字符这些功能。
Servlet API 中提供了response对象的Decorator设计模式的默认实现类HttpServletResponseWrapper ,HttpServletResponseWrapper类实现了response接口中的所有方法,但这些方法的内部实现都是仅仅调用了一下所包装的的 response对象的对应方法,以避免用户在对response对象进行增强时需要实现response接口中的所有方法。
应用HttpServletResponseWrapper对象,压缩响应正文内容。
具体思路:通过filter向目标页面传递一个自定义的response对象。在自定义的response对象中,重写getOutputStream方法和getWriter方法,使目标资源调用此方法输出页面内容时,获得的是我们自定义的ServletOutputStream对象。在我们自定义的ServletOuputStream对象中,重写write方法,使写出的数据写出到一个buffer中。当页面完成输出后,在filter中就可得到页面写出的数据,从而我们可以调用GzipOuputStream对数据进行压缩后再写出给浏览器,以此完成响应正文件压缩功能。
编写压缩过滤器,代码如下:
1 public class GzipFilter implements Filter { 2 3 public void doFilter(ServletRequest req, ServletResponse resp, 4 FilterChain chain) throws IOException, ServletException { 5 6 HttpServletRequest request = (HttpServletRequest) req; 7 HttpServletResponse response = (HttpServletResponse) resp; 8 9 BufferResponse myresponse = new BufferResponse(response); 10 chain.doFilter(request, myresponse); 11 //拿出缓存中的数据,压缩后再打给浏览器 12 byte out[] = myresponse.getBuffer(); 13 System.out.println("原始大小:" + out.length); 14 15 ByteArrayOutputStream bout = new ByteArrayOutputStream(); 16 //压缩输出流中的数据 17 GZIPOutputStream gout = new GZIPOutputStream(bout); 18 gout.write(out); 19 gout.close(); 20 21 byte gzip[] = bout.toByteArray(); 22 System.out.println("压缩后的大小:" + gzip.length); 23 24 response.setHeader("content-encoding", "gzip"); 25 response.setContentLength(gzip.length); 26 response.getOutputStream().write(gzip); 27 } 28 29 public void destroy() { 30 31 } 32 33 public void init(FilterConfig filterConfig) throws ServletException { 34 35 } 36 } 37 38 class BufferResponse extends HttpServletResponseWrapper{ 39 40 private ByteArrayOutputStream bout = new ByteArrayOutputStream(); 41 private PrintWriter pw; 42 private HttpServletResponse response; 43 public BufferResponse(HttpServletResponse response) { 44 super(response); 45 this.response = response; 46 } 47 @Override 48 public ServletOutputStream getOutputStream() throws IOException { 49 return new MyServletOutputStream(bout); 50 } 51 @Override 52 public PrintWriter getWriter() throws IOException { 53 pw = new PrintWriter(new OutputStreamWriter(bout,this.response.getCharacterEncoding())); 54 return pw; 55 } 56 57 public byte[] getBuffer(){ 58 try{ 59 if(pw!=null){ 60 pw.close(); 61 } 62 if(bout!=null){ 63 bout.flush(); 64 return bout.toByteArray(); 65 } 66 67 68 return null; 69 }catch (Exception e) { 70 throw new RuntimeException(e); 71 } 72 } 73 } 74 75 class MyServletOutputStream extends ServletOutputStream{ 76 77 private ByteArrayOutputStream bout; 78 public MyServletOutputStream(ByteArrayOutputStream bout){ 79 this.bout = bout; 80 } 81 82 @Override 83 public void write(int b) throws IOException { 84 this.bout.write(b); 85 } 86 }
在web.xml中配置压缩过滤器:
1 <filter> 2 <description>配置压缩过滤器</description> 3 <filter-name>GzipFilter</filter-name> 4 <filter-class>me.gacl.web.filter.GzipFilter</filter-class> 5 </filter> 6 7 <!--jsp文件的输出的内容都经过压缩过滤器压缩后才输出 --> 8 <filter-mapping> 9 <filter-name>GzipFilter</filter-name> 10 <url-pattern>*.jsp</url-pattern> 11 <!-- 配置过滤器的拦截方式--> 12 <!-- 对于在Servlet中通过 13 request.getRequestDispatcher("jsp页面路径").forward(request, response) 14 方式访问的Jsp页面的要进行拦截 --> 15 <dispatcher>FORWARD</dispatcher> 16 <!--对于直接以URL方式访问的jsp页面进行拦截,过滤器的拦截方式默认就是 REQUEST--> 17 <dispatcher>REQUEST</dispatcher> 18 </filter-mapping> 19 <!--js文件的输出的内容都经过压缩过滤器压缩后才输出 --> 20 <filter-mapping> 21 <filter-name>GzipFilter</filter-name> 22 <url-pattern>*.js</url-pattern> 23 </filter-mapping> 24 <!--css文件的输出的内容都经过压缩过滤器压缩后才输出 --> 25 <filter-mapping> 26 <filter-name>GzipFilter</filter-name> 27 <url-pattern>*.css</url-pattern> 28 </filter-mapping> 29 <!--html文件的输出的内容都经过压缩过滤器压缩后才输出 --> 30 <filter-mapping> 31 <filter-name>GzipFilter</filter-name> 32 <url-pattern>*.html</url-pattern> 33 </filter-mapping>
对于页面中很少更新的数据,例如商品分类,为避免每次都要从数据库查询分类数据,因此可把分类数据缓存在内存或文件中,以此来减轻数据库压力,提高系统响应速度。
编写缓存数据的过滤器,代码如下:
1 public class WebResourceCachedFilter implements Filter { 2 /** 3 * @Field: map 4 * 缓存Web资源的Map容器 5 */ 6 private Map<String,byte[]> map = new HashMap<String,byte[]>(); 7 8 @Override 9 public void init(FilterConfig filterConfig) throws ServletException { 10 11 } 12 13 @Override 14 public void doFilter(ServletRequest req, ServletResponse resp, 15 FilterChain chain) throws IOException, ServletException { 16 HttpServletRequest request = (HttpServletRequest) req; 17 HttpServletResponse response = (HttpServletResponse) resp; 18 //1.得到用户请求的uri 19 String uri = request.getRequestURI(); 20 //2.看缓存中有没有uri对应的数据 21 byte b[] = map.get(uri); 22 //3.如果缓存中有,直接拿缓存的数据打给浏览器,程序返回 23 if(b!=null){ 24 //根据字节数组和指定的字符编码构建字符串 25 String webResourceHtmlStr = new String(b,response.getCharacterEncoding()); 26 System.out.println(webResourceHtmlStr); 27 response.getOutputStream().write(b); 28 return; 29 } 30 //4.如果缓存没有,让目标资源执行,并捕获目标资源的输出 31 BufferResponse myresponse = new BufferResponse(response); 32 chain.doFilter(request, myresponse); 33 //获取缓冲流中的内容的字节数组 34 byte out[] = myresponse.getBuffer(); 35 //5.把资源的数据以用户请求的uri为关键字保存到缓存中 36 map.put(uri, out); 37 //6.把数据打给浏览器 38 response.getOutputStream().write(out); 39 } 40 41 @Override 42 public void destroy() { 43 44 } 45 46 class BufferResponse extends HttpServletResponseWrapper{ 47 private ByteArrayOutputStream bout = new ByteArrayOutputStream(); //捕获输出的缓存 48 private PrintWriter pw; 49 private HttpServletResponse response; 50 public BufferResponse(HttpServletResponse response) { 51 super(response); 52 this.response = response; 53 } 54 @Override 55 public ServletOutputStream getOutputStream() throws IOException { 56 return new MyServletOutputStream(bout); 57 } 58 @Override 59 public PrintWriter getWriter() throws IOException { 60 pw = new PrintWriter(new OutputStreamWriter(bout,this.response.getCharacterEncoding())); 61 return pw; 62 } 63 64 public byte[] getBuffer(){ 65 try{ 66 if(pw!=null){ 67 pw.close(); 68 } 69 return bout.toByteArray(); 70 }catch (Exception e) { 71 throw new RuntimeException(e); 72 } 73 } 74 } 75 76 class MyServletOutputStream extends ServletOutputStream{ 77 private ByteArrayOutputStream bout; 78 public MyServletOutputStream(ByteArrayOutputStream bout){ //接收数据写到哪里 79 this.bout = bout; 80 } 81 @Override 82 public void write(int b) throws IOException { 83 bout.write(b); 84 } 85 } 86 }
在web.xml中配置Web资源缓存过滤器:
1 <filter> 2 <description>Web资源缓存过滤器</description> 3 <filter-name>WebResourceCachedFilter</filter-name> 4 <filter-class>me.gacl.web.filter.WebResourceCachedFilter</filter-class> 5 </filter> 6 7 <filter-mapping> 8 <filter-name>WebResourceCachedFilter</filter-name> 9 <!-- 映射需要缓存输出的JSP页面,这几个页面都只是单纯作为输入UI,不会有太多的变化,因此可以缓存输出 --> 10 <url-pattern>/login.jsp</url-pattern> 11 <url-pattern>/test.jsp</url-pattern> 12 <url-pattern>/test2.jsp</url-pattern> 13 </filter-mapping>
有3 个HTTP 响应头字段都可以禁止浏览器缓存当前页面,它们在 Servlet 中的示例代码如下:
1 response.setDateHeader("Expires",-1); 2 response.setHeader("Cache-Control","no-cache"); 3 response.setHeader("Pragma","no-cache");
并不是所有的浏览器都能完全支持上面的三个响应头,因此最好是同时使用上面的三个响应头。
1 public class NoCacheFilter implements Filter { 2 3 4 public void doFilter(ServletRequest req, ServletResponse resp, 5 FilterChain chain) throws IOException, ServletException { 6 //把ServletRequest强转成HttpServletRequest 7 HttpServletRequest request = (HttpServletRequest) req; 8 //把ServletResponse强转成HttpServletResponse 9 HttpServletResponse response = (HttpServletResponse) resp; 10 //禁止浏览器缓存所有动态页面 11 response.setDateHeader("Expires", -1); 12 response.setHeader("Cache-Control", "no-cache"); 13 response.setHeader("Pragma", "no-cache"); 14 15 chain.doFilter(request, response); 16 } 17 18 public void init(FilterConfig filterConfig) throws ServletException { 19 20 } 21 22 public void destroy() { 23 24 } 25 }
web.xml文件中的配置如下:
1 <filter> 2 <filter-name>NoCacheFilter</filter-name> 3 <filter-class>me.gacl.web.filter.NoCacheFilter</filter-class> 4 </filter> 5 6 <filter-mapping> 7 <filter-name>NoCacheFilter</filter-name> 8 <!--只拦截Jsp请求--> 9 <servlet-name>*.jsp</servlet-name> 10 </filter-mapping>
有些动态页面中引用了一些图片或css文件以修饰页面效果,这些图片和css文件经常是不变化的,所以为减轻服务器的压力,可以使用filter控制浏览器缓存这些文件,以提升服务器的性能。
1 public class CacheFilter implements Filter { 2 3 private FilterConfig filterConfig; 4 5 public void doFilter(ServletRequest req, ServletResponse resp, 6 FilterChain chain) throws IOException, ServletException { 7 8 HttpServletRequest request = (HttpServletRequest) req; 9 HttpServletResponse response = (HttpServletResponse) resp; 10 11 //1.获取用户想访问的资源 12 String uri = request.getRequestURI(); 13 14 //2.得到用户想访问的资源的后缀名 15 String ext = uri.substring(uri.lastIndexOf(".")+1); 16 17 //得到资源需要缓存的时间 18 String time = filterConfig.getInitParameter(ext); 19 if(time!=null){ 20 long t = Long.parseLong(time)*3600*1000; 21 //设置缓存 22 response.setDateHeader("expires", System.currentTimeMillis() + t); 23 } 24 25 chain.doFilter(request, response); 26 27 } 28 29 public void init(FilterConfig filterConfig) throws ServletException { 30 this.filterConfig = filterConfig; 31 } 32 33 public void destroy() { 34 35 } 36 }
web.xml文件中的配置如下:
1 <!-- 配置缓存过滤器 --> 2 <filter> 3 <filter-name>CacheFilter</filter-name> 4 <filter-class>me.gacl.web.filter.CacheFilter</filter-class> 5 <!-- 配置要缓存的web资源以及缓存时间,以小时为单位 --> 6 <init-param> 7 <param-name>css</param-name> 8 <param-value>4</param-value> 9 </init-param> 10 <init-param> 11 <param-name>jpg</param-name> 12 <param-value>1</param-value> 13 </init-param> 14 <init-param> 15 <param-name>js</param-name> 16 <param-value>4</param-value> 17 </init-param> 18 <init-param> 19 <param-name>png</param-name> 20 <param-value>4</param-value> 21 </init-param> 22 </filter> 23 <!-- 配置要缓存的web资源的后缀--> 24 <filter-mapping> 25 <filter-name>CacheFilter</filter-name> 26 <url-pattern>*.jpg</url-pattern> 27 </filter-mapping> 28 29 <filter-mapping> 30 <filter-name>CacheFilter</filter-name> 31 <url-pattern>*.css</url-pattern> 32 </filter-mapping> 33 34 <filter-mapping> 35 <filter-name>CacheFilter</filter-name> 36 <url-pattern>*.js</url-pattern> 37 </filter-mapping> 38 <filter-mapping> 39 <filter-name>CacheFilter</filter-name> 40 <url-pattern>*.png</url-pattern> 41 </filter-mapping>
思路是这样的:
1、在用户登陆成功后,发送一个名称为user的cookie给客户端,cookie的值为用户名和md5加密后的密码。
2、编写一个AutoLoginFilter,这个filter检查用户是否带有名称为user的cookie来,如果有,则调用dao查询cookie的用户名和密码是否和数据库匹配,匹配则向session中存入user对象(即用户登陆标记),以实现程序完成自动登陆。
核心代码如下:
处理用户登录的控制器:LoginServlet
1 public class LoginServlet extends HttpServlet { 2 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 6 String username = request.getParameter("username"); 7 String password = request.getParameter("password"); 8 9 UserDao dao = new UserDao(); 10 User user = dao.find(username, password); 11 if(user==null){ 12 request.setAttribute("message", "用户名或密码不对!!"); 13 request.getRequestDispatcher("/message.jsp").forward(request, response); 14 return; 15 } 16 request.getSession().setAttribute("user", user); 17 //发送自动登陆cookie给客户端浏览器进行存储 18 sendAutoLoginCookie(request,response,user); 19 request.getRequestDispatcher("/index.jsp").forward(request, response); 20 } 21 22 private void sendAutoLoginCookie(HttpServletRequest request, HttpServletResponse response, User user) { 23 if (request.getParameter("logintime")!=null) { 24 int logintime = Integer.parseInt(request.getParameter("logintime")); 25 //创建cookie,cookie的名字是autologin,值是用户登录的用户名和密码,用户名和密码之间使用.进行分割,密码经过md5加密处理 26 Cookie cookie = new Cookie("autologin",user.getUsername() + "." + WebUtils.md5(user.getPassword())); 27 //设置cookie的有效期 28 cookie.setMaxAge(logintime); 29 //设置cookie的有效路径 30 cookie.setPath(request.getContextPath()); 31 //将cookie写入到客户端浏览器 32 response.addCookie(cookie); 33 } 34 } 35 36 public void doPost(HttpServletRequest request, HttpServletResponse response) 37 throws ServletException, IOException { 38 39 doGet(request, response); 40 } 41 42 }
处理用户自动登录的过滤器:AutoLoginFilter
1 public class AutoLoginFilter implements Filter { 2 3 public void doFilter(ServletRequest req, ServletResponse resp, 4 FilterChain chain) throws IOException, ServletException { 5 6 HttpServletRequest request = (HttpServletRequest) req; 7 HttpServletResponse response = (HttpServletResponse) resp; 8 //如果已经登录了,就直接chain.doFilter(request, response)放行 9 if(request.getSession().getAttribute("user")!=null){ 10 chain.doFilter(request, response); 11 return; 12 } 13 14 //1.得到用户带过来的authlogin的cookie 15 String value = null; 16 Cookie cookies[] = request.getCookies(); 17 for(int i=0;cookies!=null && i<cookies.length;i++){ 18 if(cookies[i].getName().equals("autologin")){ 19 value = cookies[i].getValue(); 20 } 21 } 22 23 //2.得到 cookie中的用户名和密码 24 if(value!=null){ 25 String username = value.split("\\.")[0]; 26 String password = value.split("\\.")[1]; 27 28 //3.调用dao获取用户对应的密码 29 UserDao dao = new UserDao(); 30 User user = dao.find(username); 31 String dbpassword = user.getPassword(); 32 33 //4.检查用户带过来的md5的密码和数据库中的密码是否匹配,如匹配则自动登陆 34 if(password.equals(WebUtils.md5(dbpassword))){ 35 request.getSession().setAttribute("user", user); 36 } 37 } 38 39 chain.doFilter(request, response); 40 } 41 42 public void destroy() { 43 44 } 45 46 public void init(FilterConfig filterConfig) throws ServletException { 47 48 } 49 }
如果想取消自动登录,那么可以在用户注销时删除自动登录cookie,核心代码如下:
1 public class CancelAutoLoginServlet extends HttpServlet { 2 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 //移除存储在session中的user 6 request.getSession().removeAttribute("user"); 7 //移除自动登录的cookie 8 removeAutoLoginCookie(request,response); 9 //注销用户后跳转到登录页面 10 request.getRequestDispatcher("/login.jsp").forward(request, response); 11 } 12 13 /** 14 * @Method: removeAutoLoginCookie 15 * @Description: 删除自动登录cookie, 16 * JavaWeb中删除cookie的方式就是新创建一个cookie,新创建的cookie与要删除的cookie同名, 17 * 设置新创建的cookie的cookie的有效期设置为0,有效路径与要删除的cookie的有效路径相同 18 * @param request 19 * @param response 20 */ 21 private void removeAutoLoginCookie(HttpServletRequest request, HttpServletResponse response) { 22 //创建一个名字为autologin的cookie 23 Cookie cookie = new Cookie("autologin",""); 24 //将cookie的有效期设置为0,命令浏览器删除该cookie 25 cookie.setMaxAge(0); 26 //设置要删除的cookie的path 27 cookie.setPath(request.getContextPath()); 28 response.addCookie(cookie); 29 } 30 31 public void doPost(HttpServletRequest request, HttpServletResponse response) 32 throws ServletException, IOException { 33 doGet(request, response); 34 } 35 }
以上就是过滤器的几个常见应用场景。
标签:
原文地址:http://www.cnblogs.com/wang-meng/p/5585882.html