天天看点

使用内嵌TOMCAT 7 开发spring mvc 项目<dependency>  <groupId>org.apache.tomcat.maven</groupId>  <artifactId>tomcat7-maven-plugin</artifactId>  <version>2.2</version>  <scope>provided</scope></dependency>

1、依赖POM

<dependency>

  <groupId>org.apache.tomcat.maven</groupId>

  <artifactId>tomcat7-maven-plugin</artifactId>

  <version>2.2</version>

  <scope>provided</scope>

</dependency>

2、相关代码

import java.io.File;

import org.apache.catalina.Context;

import org.apache.catalina.Host;

import org.apache.catalina.LifecycleException;

import org.apache.catalina.core.StandardContext;

import org.apache.catalina.startup.ContextConfig;

import org.apache.catalina.startup.Tomcat;

import org.apache.naming.resources.VirtualDirContext;

public class Bootstrap {

    public static void main(String[] args) throws Exception {

        final String workspace = System.getProperty("user.dir");

        final String target = new File(workspace,"target/classes").getPath();

        final String defaultWebXml = new File(workspace,"target/test-classes/web.xml").getPath();

        final String webapp = new File(workspace,"src/main/webapp").getPath();

        Tomcat tomcat = new Tomcat(){

            public Context addWebapp(Host host, String url, String name, String path) {

                Context ctx = new StandardContext();

                ctx.setName(name);

                ctx.setPath(url);

                ctx.setDocBase(path);

                ContextConfig ctxCfg = new ContextConfig();

                ctx.addLifecycleListener(ctxCfg);

                ctxCfg.setDefaultWebXml(defaultWebXml);

                if (host == null) {

                    getHost().addChild(ctx);

                } else {

                    host.addChild(ctx);

                }

                return ctx;

            }

        };

        tomcat.getHost().setAppBase("webapp");

        StandardContext context = (StandardContext)tomcat.addWebapp("/OMCCWEB", webapp);

        VirtualDirContext resources = new VirtualDirContext();

        resources.setExtraResourcePaths("WEB-INF/classes="+target);

        context.setResources(resources);

        tomcat.setPort(8080);

        tomcat.start();

        tomcat.getServer().await();

    }

}