Servlet中转发地址出错,是怎么回事?

新手上路,请多包涵

maven的webapp项目,运行之后发现Servlet中的转发出现问题。
index.jsp:

<%
    response.sendRedirect(request.getContextPath() + "/bookServlet?method=getBooks");
%>

servlet:

public class BookServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    BookService bookService = new BookService();

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String methodName = request.getParameter("method");

        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    protected void getBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNoStr = request.getParameter("pageNo");
        String minPriceStr = request.getParameter("minPrice");
        String maxPriceStr = request.getParameter("maxPrice");

        int pageNo = 1;
        int minPrice= 0;
        int maxPrice = Integer.MAX_VALUE;

        try {
            pageNo = Integer.parseInt(pageNoStr);
        } catch (NumberFormatException e) {}

        try {
            minPrice = Integer.parseInt(minPriceStr);
        } catch (NumberFormatException e) {}

        try {
            maxPrice = Integer.parseInt(maxPriceStr);
        } catch (NumberFormatException e) {}

        CriteriaBook criteriaBook = new CriteriaBook(minPrice, maxPrice, pageNo);
        Page<Book> page = bookService.getPage(criteriaBook);

        request.setAttribute("bookpage", page);

        request.getRequestDispatcher("/WEB-INF/pages/books.jsp").forward(request, response);
        System.out.println(request.getContextPath());
    }
}

项目目录:
图片描述

debug后发现在 request.getRequestDispatcher("/WEB-INF/pages/books.jsp").forward(request, response);前符合预期结果,进行转发后出现404页面:
图片描述
求解答,谢谢!

阅读 1.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题