JSP无法识别Servlet报404错误:Web应用开发技术求助
Hey there, let's work through this 404 issue with your JSP and Servlet setup—I've dealt with this exact problem plenty of times, so here are the key checks and fixes to try:
1. Verify Servlet Mapping is Correct
This is the #1 cause of 404s between JSP and Servlet. There are two ways to map your Servlet, make sure you're using one correctly:
Traditional web.xml Mapping
If you're using a deployment descriptor, ensure your Servlet is registered and mapped properly in WEB-INF/web.xml:
<servlet> <servlet-name>CardSelectionServlet</servlet-name> <servlet-class>com.yourpackage.CardSelectionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CardSelectionServlet</servlet-name> <url-pattern>/CardSelectionServlet</url-pattern> </servlet-mapping>
Annotation-Based Mapping (Servlet 3.0+)
If you're using annotations (no web.xml needed), add the @WebServlet annotation to your Servlet class with the correct path:
@WebServlet("/CardSelectionServlet") public class CardSelectionServlet extends HttpServlet { // Your doGet/doPost logic here }
Critical Note: The action attribute in your JSP form must match the url-pattern exactly (it's case-sensitive!).
2. Fix Form Action Pathing
Your current JSP form has <form action="..."—replace that placeholder with a valid path. To avoid context path issues (like if your app is deployed under a custom name), use the JSP implicit context path variable:
<form action="${pageContext.request.contextPath}/CardSelectionServlet" method="POST"> <!-- Add your form inputs here --> </form>
Using ${pageContext.request.contextPath} ensures the form points to the correct URL regardless of your app's deployment context.
3. Check Servlet Package & Compilation
- Never use the default package: Servlets in the default package (no
packagedeclaration) can't be mapped properly by most Servlet containers. Make sure your Servlet is in a named package likecom.example.servlets. - Confirm compilation: Check that your Servlet class is compiled into
WEB-INF/classesin your deployed WAR. If it's missing, clean and rebuild your project in your IDE—sometimes build artifacts get stuck.
4. Verify Server Deployment & Restart
- Ensure your web app is fully deployed to your server (Tomcat, Jetty, etc.). Check the server's log files for any deployment errors (like missing dependencies or invalid XML).
- Restart your server: After making changes to
web.xmlor Servlet annotations, server caches can hold old configurations—restarting ensures the new mappings are loaded.
5. Double-Check for Typos
It sounds silly, but typos are one of the most common fixes. Make sure:
- The Servlet class name in
web.xmlmatches the actual class name. - The
url-patternmatches the form'sactionvalue (case matters—/Cardservlet≠/CardServlet).
内容的提问来源于stack exchange,提问作者Ran_Macavity

