1. 程式人生 > >“HTTP/1.1 405 Method not allowed”問題和java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet問題

“HTTP/1.1 405 Method not allowed”問題和java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet問題

今天想再玩一下servlet,不用任何框架。

我是用IDEA直接匯入的jar檔案,新建一個HelloServlet繼承HttpServlet。

問題一:在啟動tomcat的時候,報錯:java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest 

可以確定是有jar包的,不然就會找不到HttpServlet,這個HelloServlet編譯就會通過。

package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * helloservlet類
 *
 * @author kimtian
 */
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getProtocol());
        System.out.println("處理get請求。。。。");
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        out.println("<strong>Hello Get Servlet</strong><br>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("處理post請求。。。。");
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        out.print("<strong>Hello Post Servlet</strong><br>");
    }
}

查了一下說是tomcat的jar和專案的jar包衝突的問題。

然後我把這個jar丟到tomcat包的lib下,引用了Tomcat jar,進行了嘗試。完美解決這個問題。

 

問題二:後來啟動成功,在進行訪問的時候報錯:HTTP Status 405 ? Method Not Allowed

查了一下,發現是我再重寫doGet方法的時候,忘記去掉

super.doGet(request,response);

 這行程式碼。

查了一下原因,當協議名稱結尾為1.1的話就會報錯,405   http.method_get_not_supported

列印輸出了一下我的:request.getProtocol();

結果為:

原始碼如下:

 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_get_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }

    }