一、创建maven项目
org.apache.maven.archetypes:maven-archetype-webapp
二、增加Servlet依赖
tomcat9及以前依赖
<!--加入servlet依赖(servlet的jar)--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><!--jsp的依赖(jsp相关的jar加进来)--><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version><scope>provided</scope></dependency>
tomcat10(案例使用tomcat10)
<dependency><groupId>jakarta.servlet</groupId><artifactId>jakarta.servlet-api</artifactId><version>6.0.0</version><scope>provided</scope></dependency><dependency><groupId>jakarta.servlet.jsp</groupId><artifactId>jakarta.servlet.jsp-api</artifactId><version>3.1.1</version><scope>provided</scope></dependency>
三、创建java目录编写代码
创建java目录
创建包
创建Servlet01类并实现Servlet
package com.minos.servlet;import jakarta.servlet.*;import java.io.IOException;public class Servlet01 implements Servlet {@Overridepublic void init(ServletConfig servletConfig) throws ServletException {}@Overridepublic ServletConfig getServletConfig() {return null;}@Overridepublic void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {System.out.println("hello servlet");}@Overridepublic String getServletInfo() {return null;}@Overridepublic void destroy() {}
}
三、配置web.xml
<!DOCTYPE web-app PUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaeehttps://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"version="5.0"metadata-complete="false"><!--<web-app>--><display-name>Archetype Created Web Application</display-name><!-- 配置servlet--><servlet><servlet-name>demo01</servlet-name><servlet-class>com.minos.servlet.Servlet01</servlet-class></servlet><!-- 配置路径--><servlet-mapping><servlet-name>demo01</servlet-name><url-pattern>/demo01</url-pattern></servlet-mapping>
</web-app>
四、配置启动环境
如果本地没有安装tomcat,可以安装
https://tomcat.apache.org/
按需下载
https://dlcdn.apache.org/tomcat/tomcat-10/v10.1.10/bin/apache-tomcat-10.1.10-windows-x64.zip
解压到特定目录
D:\ProgramFiles\apache-tomcat-10.1.10\bin
配置环境变量
IDEA配置tomcat
配置默认浏览器 、端口
应用上下文配置/
五、启动应用并测试
访问
http://localhost:8080/demo01
查看控制台输出