使用装饰着模式需要有三个步骤,
- 装饰者和被装饰者实现相同的接口
- 装饰者内部包含被装饰者的引用
- 重写被装饰者的同名方法,进行功能增强
package com.store.filter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
//装饰者和被装饰者实现相同的接口,这里本应该implements HttpServletRequest,
//然而HttpServletRequestWrapper类采用了配置器设计模式,
//重写了HttpServletRequest的所有方法,以便于对接下来,增强HttpServletRequest二进一步开发,
//所以这里extends HttpServletRequestWrapper ,如果implements HttpServletRequest还要重写
//HttpServletRequest中所有的方法,这也是装饰者模式的弊端,
//如果增强类中的一个方法,需要将类中的所有方法进行重写
public class MyHttpServletRequst extends HttpServletRequestWrapper {
private HttpServletRequest request;
//装饰者内部包含被装饰者的引用
public MyHttpServletRequst(HttpServletRequest request) {
super(request);
this.request = request;
}
//重写被装饰者的同名方法,进行功能增强
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> map = new HashMap<>();
boolean hasEncode = false;
if (!hasEncode) {
if ("get".equalsIgnoreCase(request.getMethod())) {
map = request.getParameterMap();
String newKey = null;
String newValue = null;
try {
for (String key : map.keySet()) {
newKey = new String(key.getBytes("ISO-8859-1"), "UTF-8");
String[] values = map.get(key);
for (int i = 0; i < values.length; i++) {
newValue = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
values[i] = newValue;
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("post".equalsIgnoreCase(request.getMethod())) {
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map = request.getParameterMap();
}
hasEncode = true;
}
return map;
}
@Override
public String getParameter(String name) {
Map<String, String[]> map = getParameterMap();
String[] strings = map.get(name);
if (strings == null) {
return null;
} else {
return strings[0];
}
}
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> map = getParameterMap();
String[] strings = map.get(name);
return strings;
}
}