代理的模式分为3种:
静态代理,动态代理,Cglib代理
今天说说静态代理,
动态代理,主要用于字符编码
Cglib代理:没有使用过
在Spring的AOP编程中:
如果加入容器的目标对象有实现接口,用JDK代理,也即是动态代理
如果目标对象没有实现接口,用Cglib代理
静态代理的实现
首先写个接口
public interface agentInterface {
public void dealTask(String taskName);
}
第二步:委托类
public class realclass implements agentInterface{
@Override
public void dealTask(String taskName) {
System.out.print("正在处理任务"+taskName);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第三步:代理类
public class proxyClass implements agentInterface {
//代理类对于委托类的引用。
private realclass real;
public proxyClass(realclass real) {
this.real=real;
}
@Override
public void dealTask(String taskName) {
long stime = System.currentTimeMillis();
//将请求分派给委托类处理
real.dealTask(taskName);
long ftime = System.currentTimeMillis();
System.out.println("执行任务耗时"+(ftime - stime)+"毫秒");
}
}
第四步:工厂类
public class staticFactory {
public static agentInterface getInstance(){
return new proxyClass(new realclass());
}
}
第五步:测试类
public class clients {
public static void main(String args[])
{
agentInterface proxy = staticFactory.getInstance();
proxy.dealTask("linking!!!!!!!!!!!");
}
}
动态代理:字符编码
过滤类
public class GetPostEncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
//强转
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//创建普通类
RequestProxy requestProxy = new RequestProxy(request);
//设置响应类型与编码
response.setContentType("text/html;charset=UTF-8");
//发行请求,进入GetPostServlet
chain.doFilter(requestProxy.getProxy(),response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
代理类
/**
* @author Administrator
* 用于产生HttpServletRequest的动态代理对象
*/
class RequestProxy{
/**
* 目标对象
*/
private HttpServletRequest request;
/**
* 通过构造器为request设置值
*/
public RequestProxy(HttpServletRequest request) {
this.request = request;
}
/**
* 产生HttpServletRequest的代理对象(重点)
*/
public HttpServletRequest getProxy(){
return (HttpServletRequest)Proxy.newProxyInstance(
this.getClass().getClassLoader(),
request.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method,Object[] args) throws Throwable {
Object returnValue = "";
String methodName = method.getName();
if("getParameter".equals(methodName)){
//获取客户端请求的类型
String requestType = request.getMethod();
//如果是GET请求的话
if("GET".equals(requestType)){
//获取表单提交的用户名和性别
String temp = (String) method.invoke(request,args);
//如果非空
if(temp!=null && temp.trim().length()>0){
//转还
byte[] buf = temp.getBytes("ISO8859-1");
//手工装配
returnValue = new String(buf,"UTF-8");
}
//如果是POST请求的话
}else if("POST".equals(requestType)){
//设置编码方式
request.setCharacterEncoding("UTF-8");
//获取表单提交的用户名和性别
returnValue = method.invoke(request,args);
}
}else{
returnValue = method.invoke(request,args);
}
return returnValue;
}
});
}
}
网友评论