创建maven项目并引入依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>10.0.8</version>
</dependency>
代码TomcatTest
public class TomcatTest {
public static void main(String[] args) throws LifecycleException {
Tomcat tomcat = new Tomcat();
Connector connector = new Connector();
connector.setPort(8081);
connector.setURIEncoding("UTF-8");
tomcat.getService().addConnector(connector);
// http://localhost:8081/project/index.html
MyServlet myServlet = new MyServlet();
Context project = tomcat.addContext("project", null);
tomcat.addServlet(project,"myServlet",myServlet);
project.addServletMappingDecoded("/index.html","myServlet");
tomcat.start();
tomcat.getServer().await();//阻塞
}
}
代码MyServlet
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("------------servlet-----------");
}
}
启动并测试
访问 控制台打印 以上摘自网络学习视频
|