1.新建普通maven工程,添加tomcat核心依赖:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.16</version>
</dependency>
2.自定义servlet
package home.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
String pname = req.getParameter("pname");
if (pname == null) {
pname = "world";
}
PrintWriter pw = resp.getWriter();
pw.write("<h1>Hello, " + pname + "!</h1>");
pw.flush();
}
}
3.设置tomcat启动相关配置
package home;
import home.servlet.HelloServlet;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
public class APP {
public static void main(String[] args) throws Exception{
Tomcat tomcat=new Tomcat();
tomcat.setPort(8080);
StandardContext standardContext = new StandardContext();
//设置上下文路径
standardContext.setPath("/demo");
standardContext.addLifecycleListener(new Tomcat.FixContextListener());
tomcat.getHost().addChild(standardContext);
//配置servlet和映射,HelloServlet为自定义servlet
tomcat.addServlet("/demo","index",new HelloServlet());
//配置servlet路径
standardContext.addServletMappingDecoded("/index","index");
tomcat.start();
tomcat.getServer().await();
}
}
4.运行代码:出现如下内容说明启动成功
一月 29, 2023 11:41:51 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-nio-8080"]
一月 29, 2023 11:41:51 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
一月 29, 2023 11:41:51 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Tomcat]
一月 29, 2023 11:41:51 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.5.16
一月 29, 2023 11:41:51 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8080"]
5.在浏览器输入:http://localhost:8080/demo/index?pname=Mary