您的位置:首页 > 运维架构 > Tomcat

使用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')

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐