欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何用URLClassLoader来加载一个指定目录下的class类 ServletWeb

程序员文章站 2022-07-15 07:59:46
...

直接插入我的代码:

public class ServletProcessor1 {

	public void process(Request request, Response response) {
		// TODO Auto-generated method stub
		String uri = request.getUri();
		System.out.println(uri);
		String servletName = uri.substring(uri.lastIndexOf("/")+1);
		URLClassLoader loader = null;
		try{
			URL[] urls = new URL[1];
			URLStreamHandler streamHandler = null;
			File classPath = new File(Constants.WEB_ROOT);
			
			String repository = (new URL("file",null,classPath.getCanonicalPath()+File.separator)).toString();
			urls[0] = new URL(null,repository,streamHandler);
			loader = new URLClassLoader(urls);
		}catch(IOException e){
			e.printStackTrace();
		}
		Class myClass = null;
		try{
			myClass = loader.loadClass(servletName);
		}catch(ClassNotFoundException e){
			System.out.println(e.toString());
		}
		Servlet servlet = null;
		try{
			servlet = (Servlet)myClass.newInstance();
			servlet.service((ServletRequest)request, (ServletResponse)response);
		}catch(Exception e){
			System.out.println(e.toString());			
		}
	}
}

 运行时,总发现 myClass = loader.loadClass(servletName); 报错,

"servletName" 是有WebRoot/WEb-INF/CLASS文件下是有的,

不过在com/servlet_/test/包下面.

 

请高手赐教,急呀!

相关标签: Servlet Web