在filter中可以得到代表用戶請(qǐng)求和響應(yīng)的request锄蹂、response對(duì)象带饱,因此在編程中可以使用Decorator(裝飾器)模式對(duì)request典蜕、response對(duì)象進(jìn)行包裝稚伍,再把包裝對(duì)象傳給目標(biāo)資源轧叽,從而實(shí)現(xiàn)一些特殊需求苗沧。
一、Decorator設(shè)計(jì)模式
1.1炭晒、Decorator設(shè)計(jì)模式介紹
當(dāng)某個(gè)對(duì)象的方法不適應(yīng)業(yè)務(wù)需求時(shí)待逞,通常有2種方式可以對(duì)方法進(jìn)行增強(qiáng):
編寫子類,覆蓋需增強(qiáng)的方法网严。
使用Decorator設(shè)計(jì)模式對(duì)方法進(jìn)行增強(qiáng)识樱。
裝飾模式又名包裝(Wrapper)模式。裝飾模式以對(duì)客戶端透明的方式擴(kuò)展對(duì)象的功能震束,是繼承關(guān)系的一個(gè)替代方案怜庸。裝飾模式是在不必改變?cè)愇募褪褂美^承的情況下,動(dòng)態(tài)的擴(kuò)展一個(gè)對(duì)象的功能垢村。它是通過創(chuàng)建一個(gè)包裝對(duì)象割疾,也就是裝飾來包裹真實(shí)的對(duì)象。
那么在實(shí)際應(yīng)用中遇到需增強(qiáng)對(duì)象的方法時(shí)嘉栓,到底選用哪種方式比較好呢宏榕?這個(gè)沒有具體的定式,只能是根據(jù)具體的需求來采用具體的方式侵佃,不過有一種情況下麻昼,必須使用Decorator設(shè)計(jì)模式:即被增強(qiáng)的對(duì)象,開發(fā)人員只能得到它的對(duì)象趣钱,無法得到它的class文件涌献。
比如request、response對(duì)象首有,開發(fā)人員之所以在servlet中能通過sun公司定義的HttpServletRequest\response接口去操作這些對(duì)象燕垃,是因?yàn)門omcat服務(wù)器廠商編寫了request、response接口的實(shí)現(xiàn)類井联。web服務(wù)器在調(diào)用servlet時(shí)卜壕,會(huì)用這些接口的實(shí)現(xiàn)類創(chuàng)建出對(duì)象,然后傳遞給servlet程序烙常。此種情況下轴捎,由于開發(fā)人員根本不知道服務(wù)器廠商編寫的request鹤盒、response接口的實(shí)現(xiàn)類是哪個(gè)?在程序中只能拿到服務(wù)器廠商提供的對(duì)象侦副,因此就只能采用Decorator設(shè)計(jì)模式對(duì)這些對(duì)象進(jìn)行增強(qiáng)侦锯。
1.2、Decorator設(shè)計(jì)模式的實(shí)現(xiàn)
1.首先看需要被增強(qiáng)對(duì)象繼承了什么接口或父類秦驯,編寫一個(gè)類也去繼承這些接口或父類尺碰。
2.在類中定義一個(gè)變量译隘,變量類型即需增強(qiáng)對(duì)象的類型亲桥。
3.在類中定義一個(gè)構(gòu)造函數(shù)固耘,接收需增強(qiáng)的對(duì)象题篷。
4.覆蓋需增強(qiáng)的方法厅目,編寫增強(qiáng)的代碼番枚。
二毯焕、使用Decorator設(shè)計(jì)模式增強(qiáng)request對(duì)象
Servlet API 中提供了一個(gè)request對(duì)象的Decorator設(shè)計(jì)模式的默認(rèn)實(shí)現(xiàn)類HttpServletRequestWrapper鹅很,HttpServletRequestWrapper 類實(shí)現(xiàn)了request 接口中的所有方法际看,但這些方法的內(nèi)部實(shí)現(xiàn)都是僅僅調(diào)用了一下所包裝的的 request 對(duì)象的對(duì)應(yīng)方法游昼,以避免用戶在對(duì)request對(duì)象進(jìn)行增強(qiáng)時(shí)需要實(shí)現(xiàn)request接口中的所有方法错维。
2.1沐飘、使用Decorator模式包裝request對(duì)象解決get和post請(qǐng)求方式下的中文亂碼問題
編寫一個(gè)用于處理中文亂碼的過濾器CharacterEncodingFilter猛拴,代碼如下:
package me.gacl.web.filter;
import java.io.IOException;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName: CharacterEncodingFilter
* @Description: 此過濾器用來解決解決get色迂、post請(qǐng)求方式下的中文亂碼問題
* @author: 孤傲蒼狼
* @date: 2014-8-31 下午11:09:37
*
*/
public class CharacterEncodingFilter implements Filter {
private FilterConfig filterConfig = null;
//設(shè)置默認(rèn)的字符編碼
private String defaultCharset = "UTF-8";
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//得到在web.xml中配置的字符編碼
String charset = filterConfig.getInitParameter("charset");
if(charset==null){
charset = defaultCharset;
}
request.setCharacterEncoding(charset);
response.setCharacterEncoding(charset);
response.setContentType("text/html;charset="+charset);
MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request);
chain.doFilter(requestWrapper, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
//得到過濾器的初始化配置信息
this.filterConfig = filterConfig;
}
public void destroy() {
}
}
/**
* @ClassName: MyCharacterEncodingRequest
* @Description: Servlet API中提供了一個(gè)request對(duì)象的Decorator設(shè)計(jì)模式的默認(rèn)實(shí)現(xiàn)類HttpServletRequestWrapper,
* (HttpServletRequestWrapper類實(shí)現(xiàn)了request接口中的所有方法瘟忱,但這些方法的內(nèi)部實(shí)現(xiàn)都是僅僅調(diào)用了一下所包裝的的 request對(duì)象的對(duì)應(yīng)方法)
* 以避免用戶在對(duì)request對(duì)象進(jìn)行增強(qiáng)時(shí)需要實(shí)現(xiàn)request接口中的所有方法奥额。
* 所以當(dāng)需要增強(qiáng)request對(duì)象時(shí),只需要寫一個(gè)類繼承HttpServletRequestWrapper類访诱,然后在重寫需要增強(qiáng)的方法即可
* @author: 孤傲蒼狼
* @date: 2014-9-2 下午10:42:57
* 1.實(shí)現(xiàn)與被增強(qiáng)對(duì)象相同的接口
2垫挨、定義一個(gè)變量記住被增強(qiáng)對(duì)象
3、定義一個(gè)構(gòu)造函數(shù)触菜,接收被增強(qiáng)對(duì)象
4九榔、覆蓋需要增強(qiáng)的方法
5、對(duì)于不想增強(qiáng)的方法涡相,直接調(diào)用被增強(qiáng)對(duì)象(目標(biāo)對(duì)象)的方法
*/
class MyCharacterEncodingRequest extends HttpServletRequestWrapper{
//定義一個(gè)變量記住被增強(qiáng)對(duì)象(request對(duì)象是需要被增強(qiáng)的對(duì)象)
private HttpServletRequest request;
//定義一個(gè)構(gòu)造函數(shù)哲泊,接收被增強(qiáng)對(duì)象
public MyCharacterEncodingRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
/* 覆蓋需要增強(qiáng)的getParameter方法
* @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
*/
@Override
public String getParameter(String name) {
try{
//獲取參數(shù)的值
String value= this.request.getParameter(name);
if(value==null){
return null;
}
//如果不是以get方式提交數(shù)據(jù)的,就直接返回獲取到的值
if(!this.request.getMethod().equalsIgnoreCase("get")) {
return value;
}else{
//如果是以get方式提交數(shù)據(jù)的催蝗,就對(duì)獲取到的值進(jìn)行轉(zhuǎn)碼處理
value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding());
return value;
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
在web.xml文件中配置CharacterEncodingFilter
<!--配置字符過濾器切威,解決get、post請(qǐng)求方式下的中文亂碼問題-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>me.gacl.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
編寫jsp測(cè)試頁面丙号,如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<%--引入jstl標(biāo)簽庫(kù) --%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML>
<html>
<head>
<title>使用字符過濾器解決解決get先朦、post請(qǐng)求方式下的中文亂碼問題</title>
</head>
<body>
<%--使用c:url標(biāo)簽構(gòu)建url缰冤,構(gòu)建好的url存儲(chǔ)在servletDemo1變量中--%>
<c:url value="/servlet/ServletDemo1" scope="page" var="servletDemo1">
<%--構(gòu)建的url的附帶的中文參數(shù) ,參數(shù)名是:username喳魏,值是:孤傲蒼狼--%>
<c:param name="username" value="孤傲蒼狼"></c:param>
</c:url>
<%--使用get的方式訪問 --%>
<a href="${servletDemo1}">超鏈接(get方式請(qǐng)求)</a>
<hr/>
<%--使用post方式提交表單 --%>
<form action="${pageContext.request.contextPath}/servlet/ServletDemo1" method="post">
用戶名:<input type="text" name="username" value="孤傲蒼狼" />
<input type="submit" value="post方式提交">
</form>
</body>
</html>
編寫處理用戶請(qǐng)求的ServletDemo1
package me.gacl.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//接收參數(shù)
String username = request.getParameter("username");
//獲取請(qǐng)求方式
String method = request.getMethod();
//獲取輸出流
PrintWriter out = response.getWriter();
out.write("請(qǐng)求的方式:"+method);
out.write("<br/>");
out.write("接收到的參數(shù):"+username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2.2棉浸、使用Decorator模式包裝request對(duì)象實(shí)現(xiàn)html標(biāo)簽轉(zhuǎn)義功能
編寫一個(gè)html轉(zhuǎn)義過濾器,代碼如下:
package me.gacl.web.filter;
import java.io.IOException;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName: HtmlFilter
* @Description: html轉(zhuǎn)義過濾器
* @author: 孤傲蒼狼
* @date: 2014-9-2 下午11:28:41
*
*/
public class HtmlFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
MyHtmlRequest myrequest = new MyHtmlRequest(request);
chain.doFilter(myrequest, response);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
/**
* @ClassName: MyHtmlRequest
* @Description: 使用Decorator模式包裝request對(duì)象截酷,實(shí)現(xiàn)html標(biāo)簽轉(zhuǎn)義功能
* @author: 孤傲蒼狼
* @date: 2014-9-2 下午11:29:09
*
*/
class MyHtmlRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
public MyHtmlRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
/* 覆蓋需要增強(qiáng)的getParameter方法
* @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
*/
@Override
public String getParameter(String name) {
String value = this.request.getParameter(name);
if (value == null) {
return null;
}
//調(diào)用filter轉(zhuǎn)義value中的html標(biāo)簽
return filter(value);
}
/**
* @Method: filter
* @Description: 過濾內(nèi)容中的html標(biāo)簽
* @Anthor:孤傲蒼狼
* @param message
* @return
*/
public String filter(String message) {
if (message == null){
return null;
}
char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
default:
result.append(content[i]);
}
}
return result.toString();
}
}
在web.xml文件中配置HtmlFilter
<!--配置Html過濾器涮拗,轉(zhuǎn)義內(nèi)容中的html標(biāo)簽-->
<filter>
<filter-name>HtmlFilter</filter-name>
<filter-class>me.gacl.web.filter.HtmlFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HtmlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
編寫jsp測(cè)試頁面乾戏,如下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>html過濾器測(cè)試</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/ServletDemo2" method="post">
留言:
<textarea rows="8" cols="70" name="message">
<script type="text/javascript">
while(true){
alert("死循環(huán)了迂苛,我會(huì)不停地彈出了");
}
</script>
<a >訪問博客園</a>
</textarea>
<input type="submit" value="發(fā)表">
</form>
</body>
</html>
編寫處理用戶請(qǐng)求的ServletDemo2
package me.gacl.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取用戶輸入的內(nèi)容
String message = request.getParameter("message");
response.getWriter().write("您上次的留言是:<br/>" + message);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2.3、使用Decorator模式包裝request對(duì)象實(shí)現(xiàn)敏感字符過濾功能
編寫一個(gè)敏感字符過濾器鼓择,代碼如下
package me.gacl.web.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName: DirtyFilter
* @Description: 敏感詞過濾器
* @author: 孤傲蒼狼
* @date: 2014-9-6 上午10:43:11
*
*/
public class DirtyFilter implements Filter {
private FilterConfig config = null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
DirtyRequest dirtyrequest = new DirtyRequest(request);
chain.doFilter(dirtyrequest, response);
}
@Override
public void destroy() {
}
/**
* @Method: getDirtyWords
* @Description: 獲取敏感字符
* @Anthor:孤傲蒼狼
*
* @return
*/
private List<String> getDirtyWords(){
List<String> dirtyWords = new ArrayList<String>();
String dirtyWordPath = config.getInitParameter("dirtyWord");
InputStream inputStream = config.getServletContext().getResourceAsStream(dirtyWordPath);
InputStreamReader is = null;
try {
is = new InputStreamReader(inputStream,"UTF-8");
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
BufferedReader reader = new BufferedReader(is);
String line;
try {
while ((line = reader.readLine())!= null) {//如果 line為空說明讀完了
dirtyWords.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return dirtyWords;
}
/**
* @ClassName: DirtyRequest
* @Description: 使用Decorator模式包裝request對(duì)象三幻,實(shí)現(xiàn)敏感字符過濾功能
* @author: 孤傲蒼狼
* @date: 2014-9-6 上午11:56:35
*
*/
class DirtyRequest extends HttpServletRequestWrapper{
private List<String> dirtyWords = getDirtyWords();
private HttpServletRequest request;
public DirtyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
/* 重寫getParameter方法,實(shí)現(xiàn)對(duì)敏感字符的過濾
* @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
*/
@Override
public String getParameter(String name) {
String value = this.request.getParameter(name);
if(value==null){
return null;
}
for(String dirtyWord : dirtyWords){
if(value.contains(dirtyWord)){
System.out.println("內(nèi)容中包含敏感詞:"+dirtyWord+"呐能,將會(huì)被替換成****");
//替換敏感字符
value = value.replace(dirtyWord, "****");
}
}
return value;
}
}
}
在web.xml文件中配置DirtyFilter
<!--配置敏感字符過濾器-->
<filter>
<filter-name>DirtyFilter</filter-name>
<filter-class>me.gacl.web.filter.DirtyFilter</filter-class>
<!-- 配置要過濾的敏感字符文件 -->
<init-param>
<param-name>dirtyWord</param-name>
<param-value>/WEB-INF/DirtyWord.txt</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DirtyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
當(dāng)用戶填寫的內(nèi)容包含一些敏感字符時(shí)念搬,在DirtyFilter過濾器中就會(huì)將這些敏感字符替換掉。
我們?nèi)绻麑⑸鲜龅腃haracterEncodingFilter摆出、HtmlFilter朗徊、DirtyFilter這三個(gè)過濾器聯(lián)合起來使用,那么就相當(dāng)于是把request對(duì)象包裝了3次偎漫,request對(duì)象的getParameter方法經(jīng)過3次重寫爷恳,使得getParameter方法的功能大大增強(qiáng),可以同時(shí)解決中文亂碼象踊,html標(biāo)簽轉(zhuǎn)義温亲,敏感字符過濾這些需求。
==在實(shí)際開發(fā)中完全可以將上述的三個(gè)過濾器合并成一個(gè)杯矩,讓合并后的過濾器具有解決中文亂碼栈虚,html標(biāo)簽轉(zhuǎn)義,敏感字符過濾這些功能史隆,例如:==
package me.gacl.web.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName: AdvancedFilter
* @Description: 這個(gè)過濾器是用來解決中文亂碼魂务,轉(zhuǎn)義內(nèi)容中的html標(biāo)簽,過濾內(nèi)容中的敏感字符的
* @author: 孤傲蒼狼
* @date: 2014-9-6 下午6:17:37
*
*/
public class AdvancedFilter implements Filter {
private FilterConfig filterConfig = null;
//設(shè)置默認(rèn)的字符編碼
private String defaultCharset = "UTF-8";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//得到過濾器的初始化配置信息
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//得到在web.xml中配置的字符編碼
String charset = filterConfig.getInitParameter("charset");
if(charset==null){
charset = defaultCharset;
}
request.setCharacterEncoding(charset);
response.setCharacterEncoding(charset);
response.setContentType("text/html;charset="+charset);
AdvancedRequest requestWrapper = new AdvancedRequest(request);
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
}
class AdvancedRequest extends HttpServletRequestWrapper{
private List<String> dirtyWords = getDirtyWords();
//定義一個(gè)變量記住被增強(qiáng)對(duì)象(request對(duì)象是需要被增強(qiáng)的對(duì)象)
private HttpServletRequest request;
//定義一個(gè)構(gòu)造函數(shù)泌射,接收被增強(qiáng)對(duì)象
public AdvancedRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
/* 覆蓋需要增強(qiáng)的getParameter方法
* @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
*/
@Override
public String getParameter(String name) {
try{
//獲取參數(shù)的值
String value= this.request.getParameter(name);
if(value==null){
return null;
}
//如果不是以get方式提交數(shù)據(jù)的粘姜,就直接返回獲取到的值
if(!this.request.getMethod().equalsIgnoreCase("get")) {
//調(diào)用filter轉(zhuǎn)義value中的html標(biāo)簽
value= filter(value);
}else{
//如果是以get方式提交數(shù)據(jù)的,就對(duì)獲取到的值進(jìn)行轉(zhuǎn)碼處理
value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding());
//調(diào)用filter轉(zhuǎn)義value中的html標(biāo)簽
value= filter(value);
}
for(String dirtyWord : dirtyWords){
if(value.contains(dirtyWord)){
System.out.println("內(nèi)容中包含敏感詞:"+dirtyWord+"魄幕,將會(huì)被替換成****");
//替換敏感字符
value = value.replace(dirtyWord, "****");
}
}
return value;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* @Method: filter
* @Description: 過濾內(nèi)容中的html標(biāo)簽
* @Anthor:孤傲蒼狼
* @param value
* @return
*/
public String filter(String value) {
if (value == null){
return null;
}
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
default:
result.append(content[i]);
}
}
return (result.toString());
}
/**
* @Method: getDirtyWords
* @Description: 獲取敏感字符
* @Anthor:孤傲蒼狼
*
* @return
*/
private List<String> getDirtyWords(){
List<String> dirtyWords = new ArrayList<String>();
String dirtyWordPath = filterConfig.getInitParameter("dirtyWord");
InputStream inputStream = filterConfig.getServletContext().getResourceAsStream(dirtyWordPath);
InputStreamReader is = null;
try {
is = new InputStreamReader(inputStream,defaultCharset);
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
BufferedReader reader = new BufferedReader(is);
String line;
try {
while ((line = reader.readLine())!= null) {//如果 line為空說明讀完了
dirtyWords.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return dirtyWords;
}
}
在web.xml文件中配置AdvancedFilter
<filter>
<filter-name>AdvancedFilter</filter-name>
<filter-class>me.gacl.web.filter.AdvancedFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>dirtyWord</param-name>
<param-value>/WEB-INF/DirtyWord.txt</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>AdvancedFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三相艇、使用Decorator設(shè)計(jì)模式增強(qiáng)response對(duì)象
Servlet API 中提供了response對(duì)象的Decorator設(shè)計(jì)模式的默認(rèn)實(shí)現(xiàn)類HttpServletResponseWrapper ,HttpServletResponseWrapper類實(shí)現(xiàn)了response接口中的所有方法纯陨,但這些方法的內(nèi)部實(shí)現(xiàn)都是僅僅調(diào)用了一下所包裝的的 response對(duì)象的對(duì)應(yīng)方法坛芽,以避免用戶在對(duì)response對(duì)象進(jìn)行增強(qiáng)時(shí)需要實(shí)現(xiàn)response接口中的所有方法留储。
3.1、response增強(qiáng)案例——壓縮響應(yīng)正文內(nèi)容
應(yīng)用HttpServletResponseWrapper對(duì)象咙轩,壓縮響應(yīng)正文內(nèi)容获讳。
具體思路:通過filter向目標(biāo)頁面?zhèn)鬟f一個(gè)自定義的response對(duì)象。在自定義的response對(duì)象中活喊,重寫getOutputStream方法和getWriter方法丐膝,使目標(biāo)資源調(diào)用此方法輸出頁面內(nèi)容時(shí),獲得的是我們自定義的ServletOutputStream對(duì)象钾菊。在我們自定義的ServletOuputStream對(duì)象中帅矗,重寫write方法,使寫出的數(shù)據(jù)寫出到一個(gè)buffer中煞烫。當(dāng)頁面完成輸出后浑此,在filter中就可得到頁面寫出的數(shù)據(jù),從而我們可以調(diào)用GzipOuputStream對(duì)數(shù)據(jù)進(jìn)行壓縮后再寫出給瀏覽器滞详,以此完成響應(yīng)正文件壓縮功能凛俱。
編寫壓縮過濾器,代碼如下:
package me.gacl.web.filter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* @ClassName: GzipFilter
* @Description: 壓縮過濾器料饥,將web應(yīng)用中的文本都經(jīng)過壓縮后再輸出到瀏覽器
* @author: 孤傲蒼狼
* @date: 2014-9-7 上午10:52:42
*
*/
public class GzipFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
BufferResponse myresponse = new BufferResponse(response);
chain.doFilter(request, myresponse);
//拿出緩存中的數(shù)據(jù)蒲犬,壓縮后再打給瀏覽器
byte out[] = myresponse.getBuffer();
System.out.println("原始大小:" + out.length);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
//壓縮輸出流中的數(shù)據(jù)
GZIPOutputStream gout = new GZIPOutputStream(bout);
gout.write(out);
gout.close();
byte gzip[] = bout.toByteArray();
System.out.println("壓縮后的大小:" + gzip.length);
response.setHeader("content-encoding", "gzip");
response.setContentLength(gzip.length);
response.getOutputStream().write(gzip);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
class BufferResponse extends HttpServletResponseWrapper{
private ByteArrayOutputStream bout = new ByteArrayOutputStream();
private PrintWriter pw;
private HttpServletResponse response;
public BufferResponse(HttpServletResponse response) {
super(response);
this.response = response;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new MyServletOutputStream(bout);
}
@Override
public PrintWriter getWriter() throws IOException {
pw = new PrintWriter(new OutputStreamWriter(bout,this.response.getCharacterEncoding()));
return pw;
}
public byte[] getBuffer(){
try{
if(pw!=null){
pw.close();
}
if(bout!=null){
bout.flush();
return bout.toByteArray();
}
return null;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class MyServletOutputStream extends ServletOutputStream{
private ByteArrayOutputStream bout;
public MyServletOutputStream(ByteArrayOutputStream bout){
this.bout = bout;
}
@Override
public void write(int b) throws IOException {
this.bout.write(b);
}
}
在web.xml中配置壓縮過濾器
<filter>
<description>配置壓縮過濾器</description>
<filter-name>GzipFilter</filter-name>
<filter-class>me.gacl.web.filter.GzipFilter</filter-class>
</filter>
<!--jsp文件的輸出的內(nèi)容都經(jīng)過壓縮過濾器壓縮后才輸出 -->
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
<!-- 配置過濾器的攔截方式-->
<!-- 對(duì)于在Servlet中通過
request.getRequestDispatcher("jsp頁面路徑").forward(request, response)
方式訪問的Jsp頁面的要進(jìn)行攔截 -->
<dispatcher>FORWARD</dispatcher>
<!--對(duì)于直接以URL方式訪問的jsp頁面進(jìn)行攔截,過濾器的攔截方式默認(rèn)就是 REQUEST-->
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<!--js文件的輸出的內(nèi)容都經(jīng)過壓縮過濾器壓縮后才輸出 -->
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>*.js</url-pattern>
</filter-mapping>
<!--css文件的輸出的內(nèi)容都經(jīng)過壓縮過濾器壓縮后才輸出 -->
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>*.css</url-pattern>
</filter-mapping>
<!--html文件的輸出的內(nèi)容都經(jīng)過壓縮過濾器壓縮后才輸出 -->
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
3.2岸啡、response增強(qiáng)案例——緩存數(shù)據(jù)到內(nèi)存
對(duì)于頁面中很少更新的數(shù)據(jù)原叮,例如商品分類,為避免每次都要從數(shù)據(jù)庫(kù)查詢分類數(shù)據(jù)凰狞,因此可把分類數(shù)據(jù)緩存在內(nèi)存或文件中篇裁,以此來減輕數(shù)據(jù)庫(kù)壓力,提高系統(tǒng)響應(yīng)速度赡若。
編寫緩存數(shù)據(jù)的過濾器达布,代碼如下:
package me.gacl.web.filter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* @ClassName: WebResourceCachedFilter
* @Description: Web資源緩存過濾器
* @author: 孤傲蒼狼
* @date: 2014-9-8 上午12:20:16
*
*/
public class WebResourceCachedFilter implements Filter {
/**
* @Field: map
* 緩存Web資源的Map容器
*/
private Map<String,byte[]> map = new HashMap<String,byte[]>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//1.得到用戶請(qǐng)求的uri
String uri = request.getRequestURI();
//2.看緩存中有沒有uri對(duì)應(yīng)的數(shù)據(jù)
byte b[] = map.get(uri);
//3.如果緩存中有,直接拿緩存的數(shù)據(jù)打給瀏覽器逾冬,程序返回
if(b!=null){
//根據(jù)字節(jié)數(shù)組和指定的字符編碼構(gòu)建字符串
String webResourceHtmlStr = new String(b,response.getCharacterEncoding());
System.out.println(webResourceHtmlStr);
response.getOutputStream().write(b);
return;
}
//4.如果緩存沒有黍聂,讓目標(biāo)資源執(zhí)行,并捕獲目標(biāo)資源的輸出
BufferResponse myresponse = new BufferResponse(response);
chain.doFilter(request, myresponse);
//獲取緩沖流中的內(nèi)容的字節(jié)數(shù)組
byte out[] = myresponse.getBuffer();
//5.把資源的數(shù)據(jù)以用戶請(qǐng)求的uri為關(guān)鍵字保存到緩存中
map.put(uri, out);
//6.把數(shù)據(jù)打給瀏覽器
response.getOutputStream().write(out);
}
@Override
public void destroy() {
}
class BufferResponse extends HttpServletResponseWrapper{
private ByteArrayOutputStream bout = new ByteArrayOutputStream(); //捕獲輸出的緩存
private PrintWriter pw;
private HttpServletResponse response;
public BufferResponse(HttpServletResponse response) {
super(response);
this.response = response;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new MyServletOutputStream(bout);
}
@Override
public PrintWriter getWriter() throws IOException {
pw = new PrintWriter(new OutputStreamWriter(bout,this.response.getCharacterEncoding()));
return pw;
}
public byte[] getBuffer(){
try{
if(pw!=null){
pw.close();
}
return bout.toByteArray();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class MyServletOutputStream extends ServletOutputStream{
private ByteArrayOutputStream bout;
public MyServletOutputStream(ByteArrayOutputStream bout){ //接收數(shù)據(jù)寫到哪里
this.bout = bout;
}
@Override
public void write(int b) throws IOException {
bout.write(b);
}
}
}
在web.xml中配置Web資源緩存過濾器
<filter>
<description>Web資源緩存過濾器</description>
<filter-name>WebResourceCachedFilter</filter-name>
<filter-class>me.gacl.web.filter.WebResourceCachedFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>WebResourceCachedFilter</filter-name>
<!-- 映射需要緩存輸出的JSP頁面身腻,這幾個(gè)頁面都只是單純作為輸入U(xiǎn)I产还,不會(huì)有太多的變化,因此可以緩存輸出 -->
<url-pattern>/login.jsp</url-pattern>
<url-pattern>/test.jsp</url-pattern>
<url-pattern>/test2.jsp</url-pattern>
</filter-mapping>