Java Web客户端index.jsp关联Restful接口出现HTTP 404 Not Found问题排查
Hey there! Let's break down why you're hitting that frustrating 404 error when interacting with your RESTful interface. A 404 means the server can't locate the resource your client is requesting, so let's walk through the most common fixes using your provided code snippet as a guide.
Common Culprits & Fixes
Verify Servlet Mapping Configuration
Your form usesaction="calcular.do", so you need to make sure this path is correctly mapped to your backend Servlet:- If you're using annotations, check that your Servlet class has
@WebServlet("/calcular.do")(note the leading slash, which ensures it's mapped relative to the app root). - If you're using
web.xml, confirm the<url-pattern>for your Servlet is set to/calcular.do, and the<servlet-name>matches the corresponding<servlet-class>entry.
Pro tip: HTTP paths are case-sensitive, so double-check that "calcular.do" matches exactly what's configured on the server.
- If you're using annotations, check that your Servlet class has
Confirm Servlet Class is Properly Deployed
Ensure your Servlet class is compiled and placed in theWEB-INF/classesdirectory of your deployed application. A missing or misnamed class will prevent the server from finding the resource. Also, check for typos in the class name or package structure in your configuration.Check Application Context Path
If your web app is deployed with a context path (e.g.,http://localhost:8080/your-factorial-app/), your form action needs to account for this. You can either:- Use an absolute path:
action="/your-factorial-app/calcular.do" - Use a relative path that correctly resolves from your
index.jsplocation (ifindex.jspis in the app root,calcular.doworks; if it's in a subfolder, you may need../calcular.do).
- Use an absolute path:
Validate Request Method Matching
Your form doesn't specify amethodattribute, so it defaults toGET. Make sure your Servlet handles GET requests:- If you've overridden
doGet()in your Servlet class, ensure it's properly implemented (not empty or throwing an unhandled error). - If you're only handling
POSTrequests indoPost(), update your form to includemethod="POST"or adddoGet()logic to your Servlet.
- If you've overridden
Inspect Server Logs
Take a look at your server's access logs (e.g., Tomcat'slocalhost_access_log.*.txt). These logs will show the exact URL the server received, like:GET /your-factorial-app/calcular.do HTTP/1.1 404This can help you spot discrepancies between the URL your client is sending and what the server expects.
内容的提问来源于stack exchange,提问作者Ives Rodriguez

