一个关于无法访问GET请求的报错

144 阅读2分钟
public class BaseServlet extends HttpServlet {
    //为什么加doGet方法,图书显示页面无form表单,jsp文件默认访问doGet方法,需要从doGet方法中调用doPost方法

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        System.out.println("action:" + action);
//        if ("login".equals(action)) {
//            System.out.println("这里正在login···");
//            login(req, resp);
//
//        } else {
//            System.out.println("这里正在regist···");
//            regist(req, resp);
//
//        }
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

BookServlet通过继承父类,可以间接继承,HttpServlet,同时可以继承父类的doPOST方法,和doGet方法 继承父类的doPOST方法是为了,调用方法list,然后经过BookServlet类传回数据给jsp页面

public class BookServlet extends BaseServlet {
    BookService bookService = new BookServiceImpl();

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    protected void queryById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询图书
        //保存到request域中
        //遍历数组
        List<Book> books = bookService.queryBooks();
        req.setAttribute("books", books);
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req, resp);
    }

.JSP代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<div>        
    <a href="manager/bookServlet?action=list">图书管理</a>
    <a href="order_manager.jsp">订单管理</a>
    <a href="../../index.jsp">返回商城</a>
</div>

访问客户端的出现的问题 image.png

由于客户端在访问时,无法访问GET方法,我搜集了大量资料,并且也尝试改url代码,jsp代码路径,不是这里的问题,而是应为url无法直接通过action=方法名来访问方法,需要调用doGet方法,doGet中调用doPost方法,转换一下,即可成功。

为什么呢?

我们来了解一下post方法get方法发送请求

首先谈谈他俩的相同之处:get和post请求传输数据没什么区别,应为HTTP协议都是基于TCP/IP应用层协议

不同点:get方法请求参数一般放在url上,而post方法请求参数一般放在body上

如get:http://www/baidu.com?username=xxx?password=nnnn

post:<form action="userServlet" method="post">

先到这里。。。