Embed Tomcat Java(内嵌tomcat启动简述)

简单记录一下内部tomcat启动

maven pom.xml

	<dependencies>
		<!-- embed tomcat dependency -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-core</artifactId>
			<version>8.5.28</version>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jasper</artifactId>
			<version>8.5.28</version>
		</dependency>

		<!-- spring dependency -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>5.0.4.RELEASE</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.0.4.RELEASE</version>
			<scope>compile</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- 添加编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

tomcat启动类

/**
 *
 * @author Programming is an art from.
 * @Description: TODO
 */
public class TomcatStart {

    public static int TOMCAT_PORT = 8080;
    public static String TOMCAT_HOSTNAME = "127.0.0.1";
    public static String WEBAPP_PATH = "src/main";
    public static String WEBINF_CLASSES = "/WEB-INF/classes";
    public static String CLASS_PATH = "target/classes";
    public static String INTERNAL_PATH = "/";

    public static void main(String[] args) throws ServletException, LifecycleException {
        TomcatStart.run();
    }

    public static void run() throws ServletException, LifecycleException {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(TomcatStart.TOMCAT_PORT);
        tomcat.setHostname(TomcatStart.TOMCAT_HOSTNAME);
        tomcat.setBaseDir("."); // tomcat 信息保存在项目下

        /*
         * https://www.cnblogs.com/ChenD/p/10061008.html
         */
        StandardContext myCtx = (StandardContext) tomcat
            .addWebapp("/access", System.getProperty("user.dir") + File.separator + TomcatStart.WEBAPP_PATH);
        /*
         * true时:相关classes | jar 修改时,会重新加载资源,不过资源消耗很大
         * autoDeploy 与这个很相似,tomcat自带的热部署不是特别可靠,效率也不高。生产环境不建议开启。
         * 相关文档:
         * http://www.blogjava.net/wangxinsh55/archive/2011/05/31/351449.html
         */
        myCtx.setReloadable(false);
        // 上下文监听器
        myCtx.addLifecycleListener(new AprLifecycleListener());

        /*String webAppMount = System.getProperty("user.dir") + File.separator + TomcatStart.CLASS_PATH;
        WebResourceRoot root = new StandardRoot(myCtx);
        root.addPreResources(
            new DirResourceSet(root, TomcatStart.WEBINF_CLASSES, webAppMount, TomcatStart.INTERNAL_PATH));*/

        // 注册servlet
        tomcat.addServlet("/access", "demoServlet", new DemoServlet());
        // servlet mapping
        myCtx.addServletMappingDecoded("/demo.do", "demoServlet");
        tomcat.start();
        tomcat.getServer().await();
    }

}

注意! contextPath不要设置为 /

否则会报错, 错误信息为以下。

警告: A context path must either be an empty string or start with a ‘/‘ and do not end with a ‘/‘. The path [/] does not meet these criteria and has been changed to []
Exception in thread "main" java.lang.NullPointerException
	at org.apache.catalina.startup.Tomcat.addServlet(Tomcat.java:341)
	at org.apache.catalina.startup.Tomcat.addServlet(Tomcat.java:325)
	at cn.learn.config.TomcatStart.run(TomcatStart.java:63)
	at cn.learn.config.TomcatStart.main(TomcatStart.java:33)

servlet class

/**
 *
 * @author Programming is an art from.
 * @Description: TODO
 */
public class DemoServlet extends HttpServlet{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("access success!!!");
    }

}

启动main方法,访问成功喽!

http://127.0.0.1:8080/access/demo.do

原文地址:https://www.cnblogs.com/knowledgemine/p/12702376.html

时间: 2024-10-22 07:29:09

Embed Tomcat Java(内嵌tomcat启动简述)的相关文章

spring boot 2 内嵌Tomcat Stopping service [Tomcat]

我在使用springboot时,当代码有问题时,发现控制台打印下面信息: Connected to the target VM, address: '127.0.0.1:42091', transport: 'socket' log4j:WARN No appenders could be found for logger (org.springframework.boot.devtools.settings.DevToolsSettings). log4j:WARN Please initia

Spring Boot启动过程(四):Spring Boot内嵌Tomcat启动

之前在Spring Boot启动过程(二)提到过createEmbeddedServletContainer创建了内嵌的Servlet容器,我用的是默认的Tomcat. private void createEmbeddedServletContainer() { EmbeddedServletContainer localContainer = this.embeddedServletContainer; ServletContext localServletContext = getServ

(023)Spring Boot之修改内嵌tomcat的3种方式

springboot内嵌了tomcat容器,可以通过3中方式来修改tomcat. (1)修改application.properties文件中属性,比如: server.port=8081 server.address=127.0.0.1 server.tomcat.accesslog.enabled=true server.tomcat.accesslog.directory=d\:/springboot/logs 端口:8081 绑定IP:上面的配置只能在浏览器输入localhost:808

swt java 内嵌ActiveX控件

这里用的是SWT/JFace开发application中SWT自带的org.eclipse.swt.ole.win32 包可以支持内嵌OLE和ActiveX. 具体用法如下: //创建一个OleFrame做为OLE(或ActiveX)的框架 OleFrame oleFrame = new OleFrame(this, SWT.NONE); //创建ActiveX的容器,其中的classID是ActiveX的classid,在注册表中可以找到 OleControlSite oleControl =

内嵌tomcat,启动报错:java.lang.ClassNotFoundException: org.apache.jasper.servlet.JspServlet

解决办法:添加maven依赖即可 原文地址:https://www.cnblogs.com/ianhuafeng/p/12584136.html

spring boot 启动web,内嵌tomcat

1.pom.xml文件配置(酌情修改) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"

内嵌Tomcat的Connector对象的静态代码块

在排查问题的过程中发现Connector对象有一个静态代码块: static { replacements.put("acceptCount", "backlog"); replacements.put("connectionLinger", "soLinger"); replacements.put("connectionTimeout", "soTimeout"); replacem

Spring Boot 源码之 内嵌Tomcat端口号赋值逻辑

一.Cumtomizer的Bean的定义 EmbeddedServletContainerAutoConfiguration.java 在处理自动配置的时候,扫描到这个Bean,注册到了BeanFactory里面 @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties

SpringBoot 取消内置Tomcat启动,改用外接Tomcat

1,修改pom.xml 1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 <!-- 去除内嵌tomcat --> 5 <exclusions> 6 <exclusion> 7 <groupId>org.springframe