“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("Hello Get Servlet
"); } @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("Hello Post Servlet
"); } }

查了一下说是tomcat的jar和项目的jar包冲突的问题。

然后我把这个jar丢到tomcat包的lib下,引用了Tomcat jar,进行了尝试。完美解决这个问题。

 

问题二:后来启动成功,在进行访问的时候报错:HTTP Status 405 ? Method Not Allowed

“HTTP/1.1 405 Method not allowed”问题和java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet问题_第1张图片

查了一下,发现是我再重写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);
        }

    }

 

你可能感兴趣的:(java)