内置tomcat使用servlet
tomcat启动类
public class AppTomcat { public static void main(String[] args) throws LifecycleException { // 创建Tomcat应用对象 Tomcat tomcat = new Tomcat(); // 设置Tomcat的端口号 tomcat.setPort(8080); // 是否设置Tomcat自动部署 tomcat.getHost().setAutoDeploy(false); // 创建上下文 StandardContext standardContext = new StandardContext(); // 设置项目名 standardContext.setPath("/sb"); // 监听上下文 standardContext.addLifecycleListener(new FixContextListener()); // 向tomcat容器对象添加上下文配置 tomcat.getHost().addChild(standardContext); // 创建Servlet tomcat.addServlet("/sb", "helloword", new HelloServlet()); // Servlet映射 standardContext.addServletMappingDecoded("/hello", "helloword"); //启动tomcat容器 tomcat.start(); //等待 tomcat.getServer().await(); } }
servlet类
public class HelloServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("hellowrld"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }