如何配置Maven自带的Tomcat?解决HttpServlet依赖缺失报错
Hey there! Let's get this sorted out for you. First, let's clear up a common misconception: that javax.servlet.http.HttpServlet error isn't a Tomcat configuration problem—it's because your project doesn't have the Servlet API dependency included in its build path. Let's fix that first, then set up the Maven Tomcat plugin properly.
Step 1: Add the Servlet API Dependency to pom.xml
Maven doesn't include the Servlet API by default because it's provided by the servlet container (like Tomcat) at runtime. So we need to add it with a provided scope (this tells Maven not to package it into your WAR, since Tomcat will supply it).
Open your project's pom.xml and add this inside the <dependencies> block:
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <!-- Match this to your Tomcat version: Tomcat 9 uses 4.0.x, Tomcat 8 uses 3.1.x, Tomcat 7 uses 3.0.x --> <scope>provided</scope> </dependency>
After adding this, refresh your Maven project (in IDEA, click the "Maven" tab and hit the refresh button; in Eclipse, right-click the project > Maven > Update Project). The error in your index.jsp should disappear immediately.
Step 2: Configure the Maven Tomcat Plugin
Now let's set up the Tomcat plugin so you can run your project directly via Maven. Add this inside the <build><plugins> block of your pom.xml:
<plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <!-- Use tomcat8-maven-plugin or tomcat9-maven-plugin if you need newer versions --> <version>2.2</version> <configuration> <port>8080</port> <!-- Customize the port if 8080 is in use --> <path>/</path> <!-- Set the base URL path (e.g., /myapp would make your app accessible at http://localhost:8080/myapp) --> <uriEncoding>UTF-8</uriEncoding> <!-- Fixes potential Chinese character encoding issues --> </configuration> </plugin>
Step 3: Run Your Project with Maven Tomcat
To start the server, open your terminal (or use your IDE's built-in terminal), navigate to your project's root directory, and run:
mvn tomcat7:run
If you used the tomcat8 or tomcat9 plugin, replace tomcat7 with tomcat8 or tomcat9 accordingly. Once the server starts, you can access your app at http://localhost:8080 (or whatever port/path you configured).
Quick Notes
- Make sure the plugin version matches your Tomcat version preference—you can check the latest plugin versions on Maven Central if needed.
- If you're using a newer Jakarta EE version (instead of javax.servlet), use
jakarta.servlet:jakarta.servlet-apias the dependency group/artifactId instead.
内容的提问来源于stack exchange,提问作者Terry Yue




