Spring-代理模式
需要了解兩個類:Proxy 代理、InvocationHandler 調用處理程序
nvocationHandler接口是proxy代理實例的調用處理程序實現的一個接口,每一個proxy代理實例都有一個關聯的調用處理程序;在代理實例調用方法時,方法調用被編碼分派到調用處理程序的invoke方法
1.接口
//租房
public interface Rent {
public void rent();
}
2.真實對象
//房東
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房東要出租房子");
}
}
3.自動生成代理類
//我們會用這個類,自動生成代理類
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
public void setRent(Rent rent){
this.rent = rent;
}
//生成得到代理類
public Object getProxy(){
//如果操作Proxy.newProxyInstance()傳回的代理物件,會呼叫invoke方法
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//處理代理實例,並返回結果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//動態代理的本質,就是使用反射機制實現
//用反射(invoke),執行接口下的方法,args 參數
seeHouse();
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seeHouse(){
System.out.println("中介帶看房子");
}
public void fare(){
System.out.println("收中介費");
}
}
4.客戶端
public class Client {
public static void main(String[] args) {
//真實角色
Host host = new Host();
//代理角色:現在沒有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通過調用程序處理角色來處理我們要調用的接口對象
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();//這裡的proxy就是動態實現生成的,我們並沒有寫
proxy.rent();
}
}
//我們會用這個類,自動生成代理類
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口(真實對象)
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理類
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
//處理代理實例,並返回結果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//利用反射
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("執行了" + msg + "方法");
}
}
先在pom.xml將對應的jar包安裝 <!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--servlet-api导入高版本的--> <dependency> <groupId>javax.servlet</groupId>
Apr 19, 2023loginController @Controller public class loginController { @RequestMapping("/main") public String main(){ return "main"; } @RequestMapping("/goLogin")
Apr 19, 2023SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。 过滤器与拦截器的区别:拦截器是AOP思想的具体应用。 过滤器 servlet规范中的一部分,任何java web工程都可以使用 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截 拦截器 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
Apr 18, 2023程式編寫1 login.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.4.js"></script> <script>
Apr 17, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up