使用main方法启动一个tomcat
2017-11-11 13:51
435 查看
package org.huluo.embedTomcat; import org.apache.catalina.LifecycleException; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import java.io.IOException; public class Main { public static void main(String[] args) throws LifecycleException, IOException { Tomcat tomcat = new Tomcat(); tomcat.setHostname("localhost"); tomcat.setPort(80); tomcat.setBaseDir("E:/embedTomcat"); String contextPath = ""; StandardContext context = new StandardContext(); context.setPath(contextPath); context.addLifecycleListener(new Tomcat.FixContextListener()); tomcat.getHost().addChild(context); tomcat.addServlet(contextPath, "hello", new EmbedTomcatServlet()); context.addServletMappingDecoded("/hello", "hello"); tomcat.start(); tomcat.getServer().await(); } }
这样可以以main方法的形式启动一个嵌入式 tomcat
但是,我们还没有servlet呢:
在写一个servlet,该servlet仅仅在页面上打印一行helloworld
package org.huluo.embedTomcat;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class EmbedTomcatServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().write("helloworld");}}
还要加入嵌入式Tomcat的依赖包哦
compile(group: 'org.apache.tomcat.embed',name: 'tomcat-embed-core',version: '8.5.14')
相关文章推荐
- ECLIPSE切换工作空间,使用插件启动TOMCAT仍启动上一个项目的解决方法
- 启动两个不使用不同端口tomcat方法
- Tomcat启动完成后再执行一个指定的方法 - 不影响Tomcat的启动时间
- 在启动tomcat服务器时候加载一个action的方法
- main方法启动tomcat支持的WebSocke…
- java.lang.OutOfMemoryError:Java heap space解决方法(项目中直接运行main方法,做案例,没有启动tomcat的情况)
- java-一个简单的访问DB的main方法使用
- Intellij IDEA 的maven多模块中其中一个模块下的main方法启动报 错误:找不到或无法加载主类xxx.xxx.xxx
- 使用dubbo的main方法启动服务
- 扩大myeclipse中tomcat启动后使用的内存方法
- 详解IDEA 启动tomcat 端口占用原因以及解决方法( 使用debug模式)
- main方法启动jetty java嵌入式web服务器jetty的使用
- SpringBoot学习(三),两种启动方式-以main方法启动和在tomcat里启动
- Tomcat服务启动限制日志过大的方法、使用管理员启动,注册服务删除服务
- 使用java写一个没有main方法的“Hello World”程序(摘自java核心技术.卷I)
- Tomcat启动完成后再执行一个指定的方法 - 不影响Tomcat的启动时间
- 右击main 方法运行正常,启动tomcat 后,spring boot 项目 出现参数字符串是乱码的情况
- 同一个账号启动两个resin而要求使用不同jdk的解决方法
- 使用JMX查看一个简单的main方法运行有多少个线程参与
- WinCE C#程序,控制启动时仅仅能启动一个程序,使用相互排斥量来实现,该实现方法測试通过