【问题标题】:SERVLET - HTTP Status 405 – Method Not AllowedSERVLET - HTTP 状态 405 - 不允许的方法
【发布时间】:2021-06-04 17:14:02
【问题描述】:

index.html

<!DOCTYPE html>
<html>

<body>
 <form action="MyServlet">
  <input type="submit" value="Get Count">
 </form>
</body>
</html>

MyServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
@WebServlet(urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet  {

    private String mymsg;
    //private String message;
    int  hc;

       public void init() throws ServletException {
          mymsg = "Hello World!";
          hc=0;
          //message = "Hey";
       }

       public void doGet(HttpServletRequest request, 
          HttpServletResponse response)
          throws ServletException, IOException 
       {

          // Setting up the content type of webpage
          response.setContentType("text/html");

          // Writing message to the web page
          PrintWriter out = response.getWriter();
          out.println("<h1>" + mymsg + "</h1>");
          out.println("Count: ");
          out.println(hc++);
       }

       public void destroy() {
          
       }
    }

当我运行这个我得到错误:

HTTP 状态 405 - 方法不允许

类型状态报告

此 URL 不支持消息 HTTP 方法 POST

描述在请求行中接收到的方法是源服务器已知的,但目标资源不支持。

================================================ ====

我不明白为什么,因为我只使用 get 方法,根本不使用 post...请帮助

【问题讨论】:

  • 尝试将method="get" 添加到&lt;input&gt;&lt;form&gt; 元素。 (不知道为什么有必要,因为 HTML 规范说默认方法是 GET。)
  • 这是什么服务器运行时?
  • 你没有运行你认为你正在运行的代码。清理、重建、重新部署、重启等

标签: java eclipse servlets


【解决方案1】:

在那个 servlet 中没有实现相应的 POST 方法处理。 为了解决这个从 HttpServlet 覆盖下面的方法,

void javax.servlet.http.HttpServlet.doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

示例代码,

@WebServlet(urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet  {

private String mymsg;
//private String message;
int  hc;

   public void init() throws ServletException {
      mymsg = "Hello World!";
      hc=0;
      //message = "Hey";
   }

   public void doGet(HttpServletRequest request, 
      HttpServletResponse response)
      throws ServletException, IOException 
   {

      // Setting up the content type of webpage
      response.setContentType("text/html");

      // Writing message to the web page
      PrintWriter out = response.getWriter();
      out.println("<h1>" + mymsg + "</h1>");
      out.println("Count: ");
      out.println(hc++);
   }

   public void doPost(HttpServletRequest request, 
      HttpServletResponse response)
      throws ServletException, IOException {
      doGet(request, response);
   }
   public void destroy() {
      
   }
}

【讨论】:

猜你喜欢
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 2020-08-12
相关资源
最近更新 更多