如何解决Java Web应用中com.sun.jersey.servlet.ServletContainer类找不到异常
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer The error you're seeing means your Apache server can't locate the Jersey ServletContainer class required to run your RESTful endpoints. This almost always happens because the jersey-servlet JAR file isn't being included in the WEB-INF/lib directory of your deployed helloWorld WAR application.
Here's how to resolve this step-by-step:
1. Verify the Jersey Servlet JAR is present in your WAR
First, check if jersey-servlet-1.17.1.jar exists inside the WEB-INF/lib folder of your deployed WAR. If it's missing, Maven isn't packaging the dependency correctly into your build.
To fix this:
- Run the Maven command to clean and rebuild your project:
This ensures all dependencies are pulled and packaged into the WAR file located in themvn clean packagetargetdirectory.
2. Check your IDE's deployment configuration (if using Eclipse/IntelliJ)
If you're using an IDE to deploy your app, it might not include Maven dependencies by default:
- Eclipse:
- Right-click your project > Properties > Deployment Assembly.
- Look for an entry named "Maven Dependencies". If missing, click "Add" > "Java Build Path Entries" > select "Maven Dependencies" > Finish.
- Ensure it's mapped to the
/WEB-INF/libpath.
- IntelliJ:
- Go to File > Project Structure > Artifacts.
- Select your WAR artifact, then expand the "WEB-INF/lib" section.
- If
jersey-servlet-1.17.1.jarisn't listed, click the "+" button > "Library Files" > select the jersey-servlet dependency > OK.
3. Confirm your pom.xml dependency configuration
Double-check that your jersey-servlet dependency doesn't have an incorrect scope that would exclude it from the WAR. Your current configuration is correct, but ensure there's no <scope>provided</scope> tag (which tells Maven not to package the JAR, assuming the server provides it):
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> <version>1.17.1</version> <!-- No <scope> tag here is correct for packaging into the WAR --> </dependency>
4. Clear server cache and redeploy
Sometimes old cached files can cause issues:
- Stop your Apache server.
- Delete the
workdirectory (for Tomcat, this is usually intomcat_home/work). - Delete the deployed
helloWorldfolder from thewebappsdirectory. - Deploy the freshly built WAR from the
targetfolder again.
Following these steps should resolve the ClassNotFoundException and let your Jersey servlet load correctly.
内容的提问来源于stack exchange,提问作者A.Aou

