码迷,mamicode.com
首页 > 系统相关 > 详细

让Eclipse的TomcatPlugin支持Tomcat 8.x

时间:2018-07-18 00:40:36      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:Fix   compiler   bubuko   direct   hosts   conf   asn   filter   apache   

 

 

 

实现步骤:

1.下载eclipse tomcat 插件(略)

2.配置tomcat

tomcat插件下载完成后 Window-->Preperences 中找到tomcat配置项

 ?技术分享图片

 

 

3.配置server.xml

在conf/目录下找到server.xml文件,并在 Engine 标签中添加如下内容:

 

<Host name="www2.domain1.com"  appBase="webapps" unpackWARs="true" autoDeploy="true">
  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t "%r" %s %b" />
  <Context path="" reloadable="true" docBase="项目目录1\src\main\webapp" workDir="项目目录1\work" >
      <Loader className="org.apache.catalina.loader.DevLoader" reloadable="true" debug="1" useSystemClassLoaderAsParent="false" />
  </Context>
</Host>
<Host name="www2.domain2.com"  appBase="webapps" unpackWARs="true" autoDeploy="true">
  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t "%r" %s %b" />
  <Context path="" reloadable="true" docBase="项目目录2\src\main\webapp" workDir="项目目录2\work" >
      <Loader className="org.apache.catalina.loader.MyDevLoader" reloadable="true" debug="1" useSystemClassLoaderAsParent="false" />
  </Context>
</Host> 

 

 

4.配置hosts文件

在windows/system32/drivers/etc 目录下找到hosts文件,添加如下内容:

#	127.0.0.1       localhost
#	::1             localhost
127.0.0.1  	www2.domain1.com    www2.domain2.com    www2.domain3.com	

  

 

5.生成jar包

 

1.新建一个项目(或者使用原有的项目),创建一个包 名称为:org.apache.catalina.loader, 再创建一个类,名称为 MyDevLoader,拷贝下面java代码部分

备注:你可以随意创建一个包名和类名,但需要与 <Loader className="org.apache.catalina.loader.MyDevLoader" reloadable="true" debug="1" useSystemClassLoaderAsParent="false" /> 中的className保持一至即可。

2、消除编译报错的地方。主要是tomcat 中的lib目录下相关的jar包没有引入进来。

3、重新打成JAR包,命名DevloaderTomcat8.jar。

4、将这个jar文件放入tomcat 中的lib目录下。

 

package org.apache.catalina.loader;

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;

import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.LifecycleException;

/**
 * @author caoxiaobo
 * 备注:修改DevLoader源码后的,请生成jar包,然后放置tomcat中的lib目录下;
 */
public class MyDevLoader extends WebappLoader {
    private static final String info =
        "org.apache.catalina.loader.MyDevLoader/1.0"; 

    private String webClassPathFile = ".#webclasspath";
    private String tomcatPluginFile = ".tomcatplugin";
    
    public MyDevLoader() {
        super();        
    }        
    public MyDevLoader(ClassLoader parent) {
        super(parent);
    }
    
    /**
     * @see org.apache.catalina.Lifecycle#start()
     * 如果您使用的是tomcat7,此处的方法名称为start(),如果是tomcat8,此处的方法名称为startInternal()
     */
    public void startInternal() throws LifecycleException {
        log("Starting MyDevLoader");
        //setLoaderClass(DevWebappClassLoader.class.getName());
        
        // 如果是tomcat7,此处调用 start()方法,如果是tomcat8,此处调用startInternal()方法
        // super.start();    // tomcat7 
        super.startInternal(); // tomcat8
        
        ClassLoader cl = super.getClassLoader();
        if (cl instanceof WebappClassLoader == false) {
            logError("Unable to install WebappClassLoader !");
            return;
        }
        WebappClassLoader devCl = (WebappClassLoader) cl;
        
        List webClassPathEntries = readWebClassPathEntries();
        StringBuffer classpath   = new StringBuffer();
        for (Iterator it = webClassPathEntries.iterator(); it.hasNext();) {
            String entry = (String) it.next();
            File f = new File(entry);
            if (f.exists()) {
                if (f.isDirectory() && entry.endsWith("/")==false) f = new File(entry + "/");
                try {
                    URL url = f.toURL();
                    devCl.addURL(url);    // tomcat8
//                    devCl.addRepository(url.toString()); // tomcat7
                    classpath.append(f.toString() + File.pathSeparatorChar);
                    log("added " + url.toString());
                } catch (MalformedURLException e) {
                    logError(entry + " invalid (MalformedURL)");
                }
            } else {
                logError(entry + " does not exist !");
            }
        }
        /*
        try {
            devCl.loadClass("at.kase.webfaces.WebApplication");
            devCl.loadClass("at.kase.taglib.BaseTag");
            devCl.loadClass("at.kase.taglib.xhtml.XHTMLTag");
            devCl.loadClass("at.kase.common.reflect.ClassHelper");
            devCl.loadClass("javax.servlet.jsp.jstl.core.Config");
            log("ALL OKAY !");
        } catch(Exception e) {
            logError(e.toString());
        }*/
        String cp = (String)getServletContext().getAttribute(Globals.CLASS_PATH_ATTR);
        StringTokenizer tokenizer = new StringTokenizer(cp, File.pathSeparatorChar+"");
        while(tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            // only on windows 
            if (token.charAt(0)==‘/‘ && token.charAt(2)==‘:‘) token = token.substring(1);
            classpath.append(token + File.pathSeparatorChar);
        }
        //cp = classpath + cp;
        getServletContext().setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString());
        log("JSPCompiler Classpath = " + classpath);
    }
    
    protected void log(String msg) {
        System.out.println("[MyDevLoader] " + msg);
    }
    protected void logError(String msg) {
        System.err.println("[MyDevLoader] Error: " + msg);
    }
    
    protected List readWebClassPathEntries() {
        List rc = null;
                
        File prjDir = getProjectRootDir();
        if (prjDir == null) {
            return new ArrayList();
        }
        log("projectdir=" + prjDir.getAbsolutePath());
        
        // try loading tomcat plugin file
        // DON"T LOAD TOMCAT PLUGIN FILE (DOESN‘t HAVE FULL PATHS ANYMORE)
        //rc = loadTomcatPluginFile(prjDir);
        
        if (rc ==null) {
            rc = loadWebClassPathFile(prjDir);
        }
        
        if (rc == null) rc = new ArrayList(); // should not happen !
        return rc;
    }
    
    protected File getProjectRootDir() {
        File rootDir = getWebappDir();
        FileFilter filter = new FileFilter() {
            public boolean accept(File file) {
                return (file.getName().equalsIgnoreCase(webClassPathFile) ||
                        file.getName().equalsIgnoreCase(tomcatPluginFile));
            }
        };
        while(rootDir != null) {
            File[] files = rootDir.listFiles(filter);
            if (files != null && files.length >= 1) {
                return files[0].getParentFile();
            }
            rootDir = rootDir.getParentFile();
        }
        return null;
    }
    
    protected List loadWebClassPathFile(File prjDir) {
        File cpFile = new File(prjDir, webClassPathFile);
        if (cpFile.exists()) {            
            FileReader reader = null;
            try {
                List rc = new ArrayList();
                reader = new FileReader(cpFile);
                LineNumberReader lr = new LineNumberReader(reader);
                String line = null;
                while((line = lr.readLine()) != null) {
                    // convert ‘\‘ to ‘/‘
                    line = line.replace(‘\\‘, ‘/‘);
                    rc.add(line);
                }
                return rc;
            } catch(IOException ioEx) {
                if (reader != null) try { reader.close(); } catch(Exception ignored) {}
                return null;
            }            
        } else {
            return null;
        }
    }
    
/*
    protected List loadTomcatPluginFile(File prjDir) {
        File cpFile = new File(prjDir, tomcatPluginFile);
        if (cpFile.exists()) {            
            FileReader reader = null;
            try {
                StringBuffer buf = new StringBuffer();
                
                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(cpFile)));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    buf.append(inputLine);
                    buf.append(‘\n‘);
                }
                WebClassPathEntries entries = WebClassPathEntries.xmlUnmarshal(buf.toString());
                if (entries == null) {
                    log("no entries found in tomcatplugin file !");
                    return null;
                }
                return entries.getList();
            } catch(IOException ioEx) {
                if (reader != null) try { reader.close(); } catch(Exception ignored) {}
                return null;                
            }
        } else {
            return null;            
        }
    }
*/    
    protected ServletContext getServletContext() {
//        return ((Context) getContainer()).getServletContext(); // tomcat7
        return super.getContext().getServletContext();            // tomcat8
    }
    
    protected File getWebappDir() {        
        File webAppDir = new File(getServletContext().getRealPath("/"));
        return webAppDir;
    }
}

 

 

  

 

右键项目--> Properties --> Tomcat

技术分享图片

技术分享图片

 

至此我们已经配置完结了!

点击如下图标开始启动项目

技术分享图片

 

 出现如下信息表示配置成功.

 技术分享图片

 

让Eclipse的TomcatPlugin支持Tomcat 8.x

标签:Fix   compiler   bubuko   direct   hosts   conf   asn   filter   apache   

原文地址:https://www.cnblogs.com/caoxb/p/9326773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!