GlassFish服务器出现HTTP Status 405错误,NetBeans编写Servlet求助
Hey there, let's work through this HTTP 405 (Method Not Allowed) error you're facing with your NetBeans-developed Servlet deployed on GlassFish. Let's start with the critical issue in your code, then cover other potential checks.
1. Fix the Parameter Order in doGet()
The immediate red flag in your code is the reversed parameter order in the doGet method. Servlet specifications require that the HttpServletRequest comes before HttpServletResponse in the method signature.
Your current code has:
public void doGet(HttpServletResponse rs, HttpServletRequest rq) throws IOException, ServletException {
This is incorrect—Servlet containers can't recognize this as a valid doGet implementation, so they fall back to the default HttpServlet behavior, which returns a 405 error when the request method isn't handled properly.
Corrected code:
public class CheckBox23 extends HttpServlet { public void doGet(HttpServletRequest rq, HttpServletResponse rs) throws IOException, ServletException { rs.setContentType("text/html"); PrintWriter posh = rs.getWriter(); // Complete your output logic (fixed the truncated part for clarity) posh.println("<!DOCTYPE html>" + "<html>" + "<body>" + "<ul>" + "<li><b>Math Flag: </b>" + rq.getParameter("maths") + "</li>" + "<li><b>Chem Flag: </b>" + rq.getParameter("chem") + "</li>" + "</ul></body></html>"); posh.close(); } }
2. Ensure Request Method Matches Servlet Handling
If your client (like an HTML form) is sending a POST request but your Servlet only implements doGet, you'll also get a 405 error. To fix this:
- Either update your form to use
method="GET", or - Add a
doPostmethod to your Servlet that delegates todoGet:public void doPost(HttpServletRequest rq, HttpServletResponse rs) throws IOException, ServletException { doGet(rq, rs); // Reuse the doGet logic for POST requests }
3. Verify Servlet Mapping Configuration
Double-check that your Servlet is mapped correctly in either:
- The
@WebServletannotation (if using annotation-based config):@WebServlet("/CheckBox23") // Ensure this URL matches what you're accessing in the browser public class CheckBox23 extends HttpServlet { // ... your code ... } - Or the
web.xmldeployment descriptor (if using XML-based config):<servlet> <servlet-name>CheckBox23</servlet-name> <servlet-class>your.package.name.CheckBox23</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckBox23</servlet-name> <url-pattern>/CheckBox23</url-pattern> </servlet-mapping>
Make sure the URL you're accessing matches the mapped url-pattern.
4. Clean and Redeploy Your Application
Sometimes stale deployment artifacts can cause unexpected errors. In NetBeans:
- Right-click your project → Clean and Build
- Then redeploy to GlassFish (right-click the server instance → Deploy or Redeploy)
After fixing the parameter order first, redeploy and test again—this should resolve the 405 error in most cases.
内容的提问来源于stack exchange,提问作者Logan 96

