GVKun编程网logo

java proxy(java ProxySelector)

14

在本文中,我们将为您详细介绍javaproxy的相关知识,并且为您解答关于javaProxySelector的疑问,此外,我们还会提供一些关于apachemod_proxy,为跨域Ajax调用conf

在本文中,我们将为您详细介绍java proxy的相关知识,并且为您解答关于java ProxySelector的疑问,此外,我们还会提供一些关于apache mod_proxy,为跨域Ajax调用configurationProxyPass&ProxyPassReverse、apache mod_proxy,为跨域ajax调用配置ProxyPass和ProxyPassReverse、cannot be cast to javassist.util.proxy.Proxy、com.intellij.util.proxy.JavaProxyProperty的实例源码的有用信息。

本文目录一览:

java proxy(java ProxySelector)

java proxy(java ProxySelector)

以前知道使用 JDK Proxy 和 Cglib 生成动态代理类。但是每次被问到,这两者的区别,性能比较等问题的时候,总是答不出来。其实还是对这两个底层实现不够了解。

一、动态代理的使用

先来说一下 java 自带的 动态代理。JDK 的代理我们用到的就是两个类 Proxy 和 InvocationHandler

public interface FooBarService {

	int getOrder();
}
public class FooBarServiceImpl implements FooBarService{

	@Override
	public int getOrder() {
		System.out.println("真正的业务调用");
		return 1;
	}
}

 

package lujing.sample.core.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class FooBarServiceProxy implements InvocationHandler{

	private FooBarService target = null;
	
	public FooBarServiceProxy(FooBarService fooBarService){
		target = fooBarService;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("其实我是个代理");
		return method.invoke(target, args);
	}
	
	public FooBarService getProxy(){
		return (FooBarService)Proxy.newProxyInstance(FooBarServiceProxy.class.getClassLoader(), new Class[]{FooBarService.class}, this);
	}
}

运行输出:

public class Launcher {
	public static void main(String[] args) {
		FooBarServiceProxy proxy = new FooBarServiceProxy(new FooBarServiceImpl());
		FooBarService service = proxy.getProxy();
		System.out.println(service.getClass().getName());
		System.out.println(service.getOrder());
	}
}
com.sun.proxy.$Proxy0
其实我是个代理
真正的业务调用
1

二、动态代理源码分析

    @CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        if (h == null) {
            throw new NullPointerException();
        }

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         *  生成代理类
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            // 获取构造方法
            // private static final Class<?>[] constructorParams =
            // { InvocationHandler.class };
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
                // create proxy instance with doPrivilege as the proxy class may
                // implement non-public interfaces that requires a special permission
                return AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    // 实例化
                    public Object run() {
                        return newInstance(cons, ih);
                    }
                });
            } else {
                // 实例化
                return newInstance(cons, ih);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString());
        }
    }

从上面代码看出大概做了 3 步:

1. 生成了一个新的代理 Class 

2. 获取代理类的构造函数。这个代理 Class 的构造函数,需要传一个 InvocationHandler,这个 InvocationHandler 就是我们需要自己实现的接口。

3. 根据构造函数实例化一个代理类

这 3 步的核心就是生成代理类 Class

    /**
     * 生成代理Class
     */
    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }

        // 如果需要的代理Class已经创建过,就直接使用缓存
        // 否则 , 通过 ProxyClassFactory 创建代理类
        return proxyClassCache.get(loader, interfaces);
    }

proxyClassCache.get 的处理正如上面说到的:

1. 如果需要的代理 Class 已经创建过,就直接使用缓存
2. 否则,通过 ProxyClassFactory 创建代理类

    public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        expungeStaleEntries();

        // 只有被同一个 ClassLoader 加载的类,才算同一个类。所以这里Java Proxy 以 ClassLoader
        // 作为一个Key,分类去缓存
        Object cacheKey = CacheKey.valueOf(key, refQueue);

        // ClassLoader 对应的 代理信息
        ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
        if (valuesMap == null) {
            // 空的话创建
            ConcurrentMap<Object, Supplier<V>> oldValuesMap
                = map.putIfAbsent(cacheKey,
                                  valuesMap = new ConcurrentHashMap<>());
            if (oldValuesMap != null) {
                valuesMap = oldValuesMap;
            }
        }

        // subKeyFactory.apply 正真的创建 代理 Class
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;

        // 处理缓存
        while (true) {
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                V value = supplier.get();
                if (value != null) {
                    return value;
                }
            }
            // else no supplier in cache
            // or a supplier that returned null (could be a cleared CacheValue
            // or a Factory that wasn''t successful in installing the CacheValue)

            // lazily construct a Factory
            if (factory == null) {
                factory = new Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;
                }
                // else retry with winning supplier
            } else {
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    supplier = factory;
                } else {
                    // retry with current supplier
                    supplier = valuesMap.get(subKey);
                }
            }
        }
    }
@Override
        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
            // 校验
            for (Class<?> intf : interfaces) {
                /*
                 * Verify that the class loader resolves the name of this
                 * interface to the same Class object.
                 */
                Class<?> interfaceClass = null;
                try {
                    interfaceClass = Class.forName(intf.getName(), false, loader);
                } catch (ClassNotFoundException e) {
                }
                if (interfaceClass != intf) {
                    throw new IllegalArgumentException(
                        intf + " is not visible from class loader");
                }
                /*
                 * Verify that the Class object actually represents an
                 * interface.
                 */
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * Verify that this interface is not a duplicate.
                 */
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            String proxyPkg = null;     // package to define proxy class in

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
            for (Class<?> intf : interfaces) {
                int flags = intf.getModifiers();
                if (!Modifier.isPublic(flags)) {
                    String name = intf.getName();
                    int n = name.lastIndexOf(''.'');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * 代理类名称如:com.sun.proxy.$Proxy0
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * 生成二进制字节码
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces);
            try {
                // 二进制转Class,这里调的是 native 本地方法
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                /*
                 * A ClassFormatError here means that (barring bugs in the
                 * proxy class generation code) there was some other
                 * invalid aspect of the arguments supplied to the proxy
                 * class creation (such as virtual machine limitations
                 * exceeded).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

这里主要通过 ProxyGenerator.generateProxyClass 生成字节码数据,ProxyGenerator 没有源代码,不过网上查一下还是有源码的,这里参考的是 openJDK 的源码:

public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
        ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
        //真正生成字节码的方法
        final byte[] classFile = gen.generateClassFile();
        //如果saveGeneratedFiles为true 则生成字节码文件,所以在开始我们要设置这个参数
        //当然,也可以通过返回的bytes自己输出
        if (saveGeneratedFiles) {
            java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() {
                        public Void run() {
                            try {
                                int i = name.lastIndexOf(''.'');
                                Path path;
                                if (i > 0) {
                                    Path dir = Paths.get(name.substring(0, i).replace(''.'', File.separatorChar));
                                    Files.createDirectories(dir);
                                    path = dir.resolve(name.substring(i+1, name.length()) + ".class");
                                } else {
                                    path = Paths.get(name + ".class");
                                }
                                Files.write(path, classFile);
                                return null;
                            } catch (IOException e) {
                                throw new InternalError( "I/O exception saving generated file: " + e);
                            }
                        }
                    });
        }
        return classFile;
    }

核心还是在 generateClassFile () 上

private byte[] generateClassFile() {
        /* ============================================================
         * Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
         * 步骤1:为所有方法生成代理调度代码,将代理方法对象集合起来。
         */
        //增加 hashcode、equals、toString方法
        addProxyMethod(hashCodeMethod, Object.class);
        addProxyMethod(equalsMethod, Object.class);
        addProxyMethod(toStringMethod, Object.class);
        //增加接口方法
        for (Class<?> intf : interfaces) {
            for (Method m : intf.getMethods()) {
                addProxyMethod(m, intf);
            }
        }

        /*
         * 验证方法签名相同的一组方法,返回值类型是否相同;意思就是重写方法要方法签名和返回值一样
         */
        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            checkReturnTypes(sigmethods);
        }

        /* ============================================================
         * Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating.
         * 为类中的方法生成字段信息和方法信息
         */
        try {
            //增加构造方法
            methods.add(generateConstructor());
            for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
                for (ProxyMethod pm : sigmethods) {
                    // add static field for method''s Method object
                    fields.add(new FieldInfo(pm.methodFieldName,
                            "Ljava/lang/reflect/Method;",
                            ACC_PRIVATE | ACC_STATIC));
                    // generate code for proxy method and add it
                    methods.add(pm.generateMethod());
                }
            }
            //增加静态初始化信息
            methods.add(generateStaticInitializer());
        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        if (methods.size() > 65535) {
            throw new IllegalArgumentException("method limit exceeded");
        }
        if (fields.size() > 65535) {
            throw new IllegalArgumentException("field limit exceeded");
        }

        /* ============================================================
         * Step 3: Write the final class file.
         * 步骤3:编写最终类文件
         */
        /*
         * Make sure that constant pool indexes are reserved for the following items before starting to write the final class file.
         * 在开始编写最终类文件之前,确保为下面的项目保留常量池索引。
         */
        cp.getClass(dotToSlash(className));
        cp.getClass(superclassName);
        for (Class<?> intf: interfaces) {
            cp.getClass(dotToSlash(intf.getName()));
        }

        /*
         * Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table.
         * 设置只读,在这之前不允许在常量池中增加信息,因为要写常量池表
         */
        cp.setReadOnly();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);

        // 这里就是安装字节码规范写 二进制 数据了
        try {
            // u4 magic;
            dout.writeInt(0xCAFEBABE);
            // u2 次要版本;
            dout.writeShort(CLASSFILE_MINOR_VERSION);
            // u2 主版本
            dout.writeShort(CLASSFILE_MAJOR_VERSION);

            cp.write(dout);             // (write constant pool)

            // u2 访问标识;
            dout.writeShort(accessFlags);
            // u2 本类名;
            dout.writeShort(cp.getClass(dotToSlash(className)));
            // u2 父类名;
            dout.writeShort(cp.getClass(superclassName));
            // u2 接口;
            dout.writeShort(interfaces.length);
            // u2 interfaces[interfaces_count];
            for (Class<?> intf : interfaces) {
                dout.writeShort(cp.getClass(
                        dotToSlash(intf.getName())));
            }
            // u2 字段;
            dout.writeShort(fields.size());
            // field_info fields[fields_count];
            for (FieldInfo f : fields) {
                f.write(dout);
            }
            // u2 方法;
            dout.writeShort(methods.size());
            // method_info methods[methods_count];
            for (MethodInfo m : methods) {
                m.write(dout);
            }
            // u2 类文件属性:对于代理类来说没有类文件属性;
            dout.writeShort(0); // (no ClassFile attributes for proxy classes)

        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        return bout.toByteArray();
    }

这里我们很清楚的看到,在创建构造函数的时候,使用了 InvocationHandler 作为入参:

    /**
     * Generate the constructor method for the proxy class.
     */
    private MethodInfo generateConstructor() throws IOException {
        MethodInfo minfo = new MethodInfo(
            "<init>", "(Ljava/lang/reflect/InvocationHandler;)V",
            ACC_PUBLIC);

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        code_aload(1, out);

        out.writeByte(opc_invokespecial);
        out.writeShort(cp.getMethodRef(
            superclassName,
            "<init>", "(Ljava/lang/reflect/InvocationHandler;)V"));

        out.writeByte(opc_return);

        minfo.maxStack = 10;
        minfo.maxLocals = 2;
        minfo.declaredExceptions = new short[0];

        return minfo;
    }

 

    /**
     * Add another method to be proxied, either by creating a new
     * ProxyMethod object or augmenting an old one for a duplicate
     * method.
     *
     * "fromClass" indicates the proxy interface that the method was
     * found through, which may be different from (a subinterface of)
     * the method''s "declaring class".  Note that the first Method
     * object passed for a given name and descriptor identifies the
     * Method object (and thus the declaring class) that will be
     * passed to the invocation handler''s "invoke" method for a given
     * set of duplicate methods.
     */
    private void addProxyMethod(Method m, Class fromClass) {
        String name = m.getName();
        Class[] parameterTypes = m.getParameterTypes();
        Class returnType = m.getReturnType();
        Class[] exceptionTypes = m.getExceptionTypes();

        String sig = name + getParameterDescriptors(parameterTypes);
        List<ProxyMethod> sigmethods = proxyMethods.get(sig);
        if (sigmethods != null) {
            for (ProxyMethod pm : sigmethods) {
                if (returnType == pm.returnType) {
                    /*
                     * Found a match: reduce exception types to the
                     * greatest set of exceptions that can thrown
                     * compatibly with the throws clauses of both
                     * overridden methods.
                     */
                    List<Class> legalExceptions = new ArrayList<Class>();
                    collectCompatibleTypes(
                        exceptionTypes, pm.exceptionTypes, legalExceptions);
                    collectCompatibleTypes(
                        pm.exceptionTypes, exceptionTypes, legalExceptions);
                    pm.exceptionTypes = new Class[legalExceptions.size()];
                    pm.exceptionTypes =
                        legalExceptions.toArray(pm.exceptionTypes);
                    return;
                }
            }
        } else {
            sigmethods = new ArrayList<ProxyMethod>(3);
            proxyMethods.put(sig, sigmethods);
        }
        sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                       exceptionTypes, fromClass));
    }

三、反编译查看 Class 

Java 中生成的字节码是二进制数据,而且不像我们之前可以直接拿到.class 文件。那这个怎么导出呢?

这个时候,Java 代理机制就起作用了。

2.1 定义代理入口

public class Launcher {

	/**
	 * Java 代理入口
	 * @param agentArgs
	 * @param inst
	 */
	public static void premain(String agentArgs, Instrumentation inst) {
        inst.addTransformer(new ClassTransformer());
    }
}

 2.2 导出字节码处理

public class ClassTransformer implements ClassFileTransformer{

	/**
	 * JDK 生成的代理的命名: com.sun.proxy.$Proxy0
	 */
	private static final String PROXY_PREFIX = "com/sun/proxy/$Proxy";
	
	private String DEFAULT_FILE_PATH = "F://proxy.class";
	
	private String filePath = DEFAULT_FILE_PATH;
	
	@Override
	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {
		
		if(shouldExport(loader, className, classBeingRedefined)){
			doExportClass(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
		}
		return classfileBuffer;
	}

	/**
	 * 导出Class文件
	 * @param loader
	 * @param className
	 * @param classBeingRedefined
	 * @param protectionDomain
	 * @param classfileBuffer
	 */
	private void doExportClass(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) {
		try {
			FileOutputStream fos;
			File file = new File(filePath);
			if(file.exists()){
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
	        fos.write(classfileBuffer);
	        fos.close(); 
	        System.out.println("尝试将" + className + "写入到文件" + filePath + "成功");
		} catch (Exception e) {
			System.out.println("尝试将" + className + "写入到文件" + filePath + "失败");
		}

	}

	/**
	 * 是否需要导出
	 * @param loader
	 * @param className
	 * @param classBeingRedefined
	 * @return
	 */
	private boolean shouldExport(ClassLoader loader, String className,
			Class<?> classBeingRedefined) {
		return className.startsWith(PROXY_PREFIX);
	}
}

2.3 maven 打包参数,最主要是 Premain-Class 

	<build>
		<finalName>agent</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifestEntries>
							<Premain-Class>
								me.kimi.instrument.Launcher
							</Premain-Class>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>

clean package 就导出一个 agent.jar 啦

然后 run configuration  加入代理 jar:

运行一下代理类就导出到 proxy.class 文件了。然后找一个反编译软件(我的是 jad):

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 

package com.sun.proxy;

import java.lang.reflect.*;
import lujing.sample.core.proxy.FooBarService;

public final class $Proxy0 extends Proxy
    implements FooBarService
{
    
    // 构造函数,接受 InvocationHandler 参数
    public $Proxy0(InvocationHandler invocationhandler)
    {
        super(invocationhandler);
    }

    public final boolean equals(Object obj)
    {
        try
        {
            return ((Boolean)super.h.invoke(this, m1, new Object[] {
                obj
            })).booleanValue();
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final int hashCode()
    {
        try
        {
            return ((Integer)super.h.invoke(this, m0, null)).intValue();
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final int getOrder()
    {
        try
        {
            return ((Integer)super.h.invoke(this, m3, null)).intValue();
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final String toString()
    {
        try
        {
            return (String)super.h.invoke(this, m2, null);
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    private static Method m1;
    private static Method m0;
    private static Method m3;
    private static Method m2;

    static 
    {
        try
        {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
                Class.forName("java.lang.Object")
            });
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
            m3 = Class.forName("lujing.sample.core.proxy.FooBarService").getMethod("getOrder", new Class[0]);
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
        }
        catch(NoSuchMethodException nosuchmethodexception)
        {
            throw new NoSuchMethodError(nosuchmethodexception.getMessage());
        }
        catch(ClassNotFoundException classnotfoundexception)
        {
            throw new NoClassDefFoundError(classnotfoundexception.getMessage());
        }
    }
}

从上面的代码可以看到,代理类实现了需要代理的接口,同时每个方法都是委托给 InvocationHandler 的 invoke 方法。在生成代理发方法的时候,就知道 代理接口的方法是哪一个。

apache mod_proxy,为跨域Ajax调用configurationProxyPass&ProxyPassReverse

apache mod_proxy,为跨域Ajax调用configurationProxyPass&ProxyPassReverse

我正在创build一个html5 – JavaScript应用程序(用于移动设备,使用PhoneGap)。 我必须与REST服务进行交互。

该服务现在运行在"http://localhost:8080/backend/mvc/"

我正在开发我的应用程序在一个wamp服务器(apache2)( http://localhost/stage/ )我正在使用Chrome浏览器。

在执行ajax调用时,浏览器响应: XMLHttpRequest cannot load http://localhost:8080/backend/mvc/event. Origin http://localhost is not allowed by Access-Control-Allow-Origin. XMLHttpRequest cannot load http://localhost:8080/backend/mvc/event. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

飞行前OPTIONS请求故障转移HTTPS

Nginx和CORS问题

Apache和Nodejs跨域ajax问题

同一域(本地主机)上的XHR跨域错误

访问控制允许起源不允许起源 – 如何使用一个非常简单的networking堆栈和guice启用CORS

所以我find几种方法来规避这个跨域的Ajax调用问题:

1)启动chrome chrome.exe --disable-web-security =>没有区别

2)使用mod_proxyconfigurationApache来redirectstream量。

我在httpd.conf中启用了:

proxy_module proxy_connect_module proxy_http_module

我把一个.htaccess文件放在www的根目录下,内容如下:

# start mod_rewrite RewriteEngine On ProxyRequests off <Proxy> Order deny,allow Allow from all </Proxy> ProxyPass /EMBackend/ http://localhost:8080/backend/mvc/ ProxyPassReverse /EMBackend/ http://localhost:8080/backend/mvc/ RewriteRule ^/EMBackend/(.*)$ /backend/mvc/$1 [R]

我重新启动所有服务(Apache,PHP,..)

导致错误500

apache错误日志: [Tue Oct 18 14:30:11 2011] [alert] [client 127.0.0.1] C:/wamp/www/.htaccess: ProxyRequests not allowed here

任何线索如何解决这个问题?

在Apache中使用Access-Control-Allow-Origin标头处理多个域

设置Nginx允许跨域请求子域

绕过“选项请求”的authentication(所有的头都在响应中发送)

跨域jQuery AJAXfile upload

跨域分块上传使用CORS

我发现一个工作解决方案:

启用:

Loadmodulee proxy_module modules/mod_proxy.so Loadmodulee proxy_http_module modules/mod_proxy_http.so

把它放在你配置的主要部分(或者如果使用Apache虚拟主机,则需要虚拟主机):

ProxyRequests Off ProxyPreserveHost On <Proxy *> Order deny,allow Allow from all </Proxy> ProxyPass /EMBackend http://localhost:8080/backend/mvc ProxyPassReverse /EMBackend http://localhost:8080/backend/mvc <Location /EMBackend> Order allow,deny Allow from all </Location>

所以我想我不能把它放在.htaccess或我必须设置ProxyPreserveHost On 。 我将Include conf/extra/放在httpd.conf文件中,并创建了httpd-proxy.conf文件,并将其放在上面的脚本中。 重新启动Apache,它的工作!

启用代理模块后,您可以简单地在httpd.conf中添加给定的行。

ProxyPreserveHost On ProxyPass /EMBackend http://localhost:8080/backend/mvc ProxyPassReverse /EMBackend http://localhost:8080/backend/mvc

只需重新启动服务器,你就完成了。

在非常现代的Apache中,通过以下方式打开代理:

a2enmod proxy; a2enmod proxy_http

apache mod_proxy,为跨域ajax调用配置ProxyPass和ProxyPassReverse

apache mod_proxy,为跨域ajax调用配置ProxyPass和ProxyPassReverse

我正在创建一个html5-JavaScript应用(用于移动设备,使用PhoneGap)。我必须与REST服务进行交互。

该服务现在正在运行 "http://localhost:8080/backend/mvc/"

我正在wamp服务器(apache2)(http://localhost/stage/)上开发应用程序,正在使用Chrome浏览器。

当执行ajax调用时,浏览器响应: XMLHttpRequest cannot load http://localhost:8080/backend/mvc/event. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

因此,我找到了几种方法来解决此跨域Ajax调用问题:

1)起始chrome chrome.exe --disable-web-security =>没有区别

2)使用mod_proxy配置apache以重定向流量。

我在httpd.conf中启用了:

proxy_module
proxy_connect_module
proxy_http_module

.htaccess在www根目录下放置了一个文件,内容如下:

# start mod_rewrite
RewriteEngine On

ProxyRequests off
<Proxy>
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass /EMBackend/ http://localhost:8080/backend/mvc/
ProxyPassReverse /EMBackend/ http://localhost:8080/backend/mvc/
RewriteRule ^/EMBackend/(.*)$ /backend/mvc/$1 [R]

我重新启动了所有服务(apache,php等)。

导致错误500

apache错误日志: [Tue Oct 18 14:30:11 2011] [alert] [client 127.0.0.1] C:/wamp/www/.htaccess: ProxyRequests not allowed here

关于如何解决这个问题的任何线索?

cannot be cast to javassist.util.proxy.Proxy

cannot be cast to javassist.util.proxy.Proxy

问题现象:

最近在做一个 web 项目,使用的是 ssh 技术,添加 jar 依赖时不小心多加了一个:

导致报:

$$_javassist_13 cannot be cast to javassist.util.proxy.Proxy 

这个错误提示。

解决方案:

(1)检查依赖包

去除:javassist-3.11.jar 这个 jar 包。

(2)maven 依赖

在 maven 依赖中去除:

刷新项目,在次启动时,问题消失。

com.intellij.util.proxy.JavaProxyProperty的实例源码

com.intellij.util.proxy.JavaProxyProperty的实例源码

项目:intellij-ce-playground    文件:MantisRepository.java   
@NotNull
private MantisConnectPortType createSoap() throws Exception {
  if (isUseProxy()) {
    for (keyvalue<String,String> pair : HttpConfigurable.getJvmPropertiesList(false,null)) {
      String key = pair.getKey(),value = pair.getValue();
      // Axis uses another names for username and password properties
      // see http://axis.apache.org/axis/java/client-side-axis.html for complete list
      if (key.equals(JavaProxyProperty.HTTP_USERNAME)) {
        AxisProperties.setProperty("http.proxyUser",value);
      }
      else if (key.equals(JavaProxyProperty.HTTP_PASSWORD)) {
        AxisProperties.setProperty("http.proxyPassword",value);
      }
      else {
        AxisProperties.setProperty(key,value);
      }
    }
  }
  return new MantisConnectLocator().getMantisConnectPort(new URL(getUrl() + SOAP_API_LOCATION));
}
项目:intellij-ce-playground    文件:HttpConfigurable.java   
public static List<keyvalue<String,String>> getJvmPropertiesList(final boolean withAutodetection,@Nullable final URI uri) {
  final HttpConfigurable me = getInstance();
  if (! me.USE_HTTP_PROXY && ! me.USE_PROXY_PAC) {
    return Collections.emptyList();
  }
  final List<keyvalue<String,String>> result = new ArrayList<keyvalue<String,String>>();
  if (me.USE_HTTP_PROXY) {
    final boolean putCredentials = me.KEEP_PROXY_PASSWORD && StringUtil.isNotEmpty(me.PROXY_LOGIN);
    if (me.PROXY_TYPE_IS_SOCKS) {
      result.add(keyvalue.create(JavaProxyProperty.soCKS_HOST,me.PROXY_HOST));
      result.add(keyvalue.create(JavaProxyProperty.soCKS_PORT,String.valueOf(me.PROXY_PORT)));
      if (putCredentials) {
        result.add(keyvalue.create(JavaProxyProperty.soCKS_USERNAME,me.PROXY_LOGIN));
        result.add(keyvalue.create(JavaProxyProperty.soCKS_PASSWORD,me.getPlainProxyPassword()));
      }
    } else {
      result.add(keyvalue.create(JavaProxyProperty.HTTP_HOST,me.PROXY_HOST));
      result.add(keyvalue.create(JavaProxyProperty.HTTP_PORT,String.valueOf(me.PROXY_PORT)));
      result.add(keyvalue.create(JavaProxyProperty.HTTPS_HOST,me.PROXY_HOST));
      result.add(keyvalue.create(JavaProxyProperty.HTTPS_PORT,String.valueOf(me.PROXY_PORT)));
      if (putCredentials) {
        result.add(keyvalue.create(JavaProxyProperty.HTTP_USERNAME,me.PROXY_LOGIN));
        result.add(keyvalue.create(JavaProxyProperty.HTTP_PASSWORD,me.getPlainProxyPassword()));
      }
    }
  } else if (me.USE_PROXY_PAC && withAutodetection && uri != null) {
    final List<Proxy> proxies = CommonProxy.getInstance().select(uri);
    // we will just take the first returned proxy,but we have an option to test connection through each of them,// for instance,by calling prepareUrl()
    if (proxies != null && ! proxies.isEmpty()) {
      for (Proxy proxy : proxies) {
        if (isRealProxy(proxy)) {
          final SocketAddress address = proxy.address();
          if (address instanceof InetSocketAddress) {
            final InetSocketAddress inetSocketAddress = (InetSocketAddress)address;
            if (Proxy.Type.soCKS.equals(proxy.type())) {
              result.add(keyvalue.create(JavaProxyProperty.soCKS_HOST,inetSocketAddress.getHostName()));
              result.add(keyvalue.create(JavaProxyProperty.soCKS_PORT,String.valueOf(inetSocketAddress.getPort())));
            } else {
              result.add(keyvalue.create(JavaProxyProperty.HTTP_HOST,inetSocketAddress.getHostName()));
              result.add(keyvalue.create(JavaProxyProperty.HTTP_PORT,String.valueOf(inetSocketAddress.getPort())));
              result.add(keyvalue.create(JavaProxyProperty.HTTPS_HOST,inetSocketAddress.getHostName()));
              result.add(keyvalue.create(JavaProxyProperty.HTTPS_PORT,String.valueOf(inetSocketAddress.getPort())));
            }
          }
        }
      }
    }
  }
  return result;
}
项目:tools-idea    文件:HttpConfigurable.java   
public static List<keyvalue<String,String.valueOf(inetSocketAddress.getPort())));
            }
          }
        }
      }
    }
  }
  return result;
}
项目:consulo    文件:HttpConfigurable.java   
@Nonnull
public List<Pair<String,String>> getJvmProperties(boolean withAutodetection,@Nullable URI uri) {
  if (!USE_HTTP_PROXY && !USE_PROXY_PAC) {
    return Collections.emptyList();
  }

  List<Pair<String,String>> result = new ArrayList<>();
  if (USE_HTTP_PROXY) {
    boolean putCredentials = KEEP_PROXY_PASSWORD && StringUtil.isNotEmpty(getProxyLogin());
    if (PROXY_TYPE_IS_SOCKS) {
      result.add(Pair.pair(JavaProxyProperty.soCKS_HOST,PROXY_HOST));
      result.add(Pair.pair(JavaProxyProperty.soCKS_PORT,String.valueOf(PROXY_PORT)));
      if (putCredentials) {
        result.add(Pair.pair(JavaProxyProperty.soCKS_USERNAME,getProxyLogin()));
        result.add(Pair.pair(JavaProxyProperty.soCKS_PASSWORD,getPlainProxyPassword()));
      }
    }
    else {
      result.add(Pair.pair(JavaProxyProperty.HTTP_HOST,PROXY_HOST));
      result.add(Pair.pair(JavaProxyProperty.HTTP_PORT,String.valueOf(PROXY_PORT)));
      result.add(Pair.pair(JavaProxyProperty.HTTPS_HOST,PROXY_HOST));
      result.add(Pair.pair(JavaProxyProperty.HTTPS_PORT,String.valueOf(PROXY_PORT)));
      if (putCredentials) {
        result.add(Pair.pair(JavaProxyProperty.HTTP_USERNAME,getProxyLogin()));
        result.add(Pair.pair(JavaProxyProperty.HTTP_PASSWORD,getPlainProxyPassword()));
      }
    }
  }
  else if (USE_PROXY_PAC && withAutodetection && uri != null) {
    List<Proxy> proxies = CommonProxy.getInstance().select(uri);
    // we will just take the first returned proxy,by calling prepareUrl()
    if (proxies != null && !proxies.isEmpty()) {
      for (Proxy proxy : proxies) {
        if (isRealProxy(proxy)) {
          SocketAddress address = proxy.address();
          if (address instanceof InetSocketAddress) {
            InetSocketAddress inetSocketAddress = (InetSocketAddress)address;
            if (Proxy.Type.soCKS.equals(proxy.type())) {
              result.add(Pair.pair(JavaProxyProperty.soCKS_HOST,inetSocketAddress.getHostName()));
              result.add(Pair.pair(JavaProxyProperty.soCKS_PORT,String.valueOf(inetSocketAddress.getPort())));
            }
            else {
              result.add(Pair.pair(JavaProxyProperty.HTTP_HOST,inetSocketAddress.getHostName()));
              result.add(Pair.pair(JavaProxyProperty.HTTP_PORT,String.valueOf(inetSocketAddress.getPort())));
              result.add(Pair.pair(JavaProxyProperty.HTTPS_HOST,inetSocketAddress.getHostName()));
              result.add(Pair.pair(JavaProxyProperty.HTTPS_PORT,String.valueOf(inetSocketAddress.getPort())));
            }
          }
        }
      }
    }
  }
  return result;
}

今天关于java proxyjava ProxySelector的讲解已经结束,谢谢您的阅读,如果想了解更多关于apache mod_proxy,为跨域Ajax调用configurationProxyPass&ProxyPassReverse、apache mod_proxy,为跨域ajax调用配置ProxyPass和ProxyPassReverse、cannot be cast to javassist.util.proxy.Proxy、com.intellij.util.proxy.JavaProxyProperty的实例源码的相关知识,请在本站搜索。

本文标签: