[Java] 纯文本查看 复制代码
class MyInvocationHandler implements InvocationHandler{
private Waiter waiter;
public MyInvocationHandler(Waiter waiter) {
this.waiter = waiter;
}
@Override
// 执行目标对象的任何一个方法 都相当于执行了invoke方法.
/**
* proxy:产生代理对象.
* method:代表正在调用的方法.
* Object[]:在调用的方法的参数.
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// System.out.println("aaaaa");
// System.out.println(method.getName());
if("server".equals(method.getName())){
// 增强server.
System.out.println("微笑...");
return method.invoke(waiter, args);
}else{
// 不增强:
return method.invoke(waiter, args);
}
// return null;
}
}
[Java] 纯文本查看 复制代码
package com.itheima.encoding;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter(urlPatterns="/*")
public class GenericCharacterEncodingFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
// 对req产生代理对象:
HttpServletRequest myReq = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(),req.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 增强getParameter:
if("getParameter".equals(method.getName())){
// 增强.
// 根据请求方式:
String type = req.getMethod();
if("get".equalsIgnoreCase(type)){
// 调用原有的getParameter:
String value = (String)method.invoke(req, args);
String s = new String(value.getBytes("ISO-8859-1"),"UTF-8");
return s;
}else if("post".equalsIgnoreCase(type)){
req.setCharacterEncoding("UTF-8");
return method.invoke(req, args);
}
}
// 不增强:
return method.invoke(req, args);
}
});
chain.doFilter(myReq, response);
}
@Override
public void destroy() {
}
}