表单默认GET请求触发HTTP 405错误排查:重写doGet方法仍无效的原因分析
Let's break down why your default GET request is hitting a 405 error, even though you've implemented doGet() in your Servlet. Here are the most likely causes and fixes:
1. Verify Your Updated Servlet Is Properly Deployed
This is one of the most common oversights! It’s easy to tweak your Servlet code but forget to recompile or redeploy the project to Tomcat.
- Navigate to your Tomcat
webapps/[your-project-name]/WEB-INF/classes/net/codejava/javaee/folder and confirm thatHelloServlet.classincludes yourdoGet()implementation. - Clear Tomcat’s
workdirectory (to purge cached class files) and redeploy your project. Old, unupdated class files often linger and cause unexpected behavior.
2. Fix the Button’s Type to Avoid Double Submission
Your <button> tag lacks a type attribute, so browsers default it to type="submit". When clicked, this triggers two actions at once:
- The browser’s native form submit behavior
- Your
submitForm()JS function callingdemoForm.submit()again
This double submission can lead to inconsistent request methods. Fix it by explicitly setting the button’s type to button (so it only runs your JS function):
<button id="submitProject" style="font-size: 93%;" type="button" onClick='submitForm()'>Submit</button>
3. Test the GET Endpoint Directly to Isolate Issues
To rule out form submission quirks, test the Servlet’s GET endpoint directly in your browser’s address bar:
http://localhost:8080/[your-project-name]/helloServlet?yourName=TestName
- If this returns the expected
<h1>Hello TestName</h1>response, yourdoGet()method works correctly, and the problem lies with how the form submits requests. - If you still get a 405 error here, your Servlet’s
doGet()isn’t being recognized by Tomcat—your code’s method signature looks correct, so this is almost certainly a deployment issue.
4. Check Tomcat Logs for the Actual Request Method
Look at Tomcat’s access logs (in logs/localhost_access_log.*.txt) to see what HTTP method is being sent when you submit the form. You’re looking for a line like:
127.0.0.1 - - [DD/MM/YYYY:HH:MM:SS +0000] "GET /your-project/helloServlet?yourName=John HTTP/1.1" 200 27
- If the log shows a
POSTmethod instead ofGET, that explains the 405 error (since your form should default to GET). This would point to the double submission issue or a browser quirk.
5. Confirm No Accidental Parent Class Calls
You mentioned removing parent class calls, which is correct—calling super.doGet(req, resp) would trigger the default HttpServlet behavior that returns a 405 error. Your code looks clean here, but double-check that no leftover calls exist in your deployed class file.
内容的提问来源于stack exchange,提问作者user12872106

