有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何通过使用复杂的重定向从一个servlet重定向到另一个servlet?

如果我有两个servlet:

@WebServlet (urlPatterns = {"/s1"})
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("A", 100);
        map.put("B", 200);
        map.put("C", 300);

        req.setAttribute("map", map);
        getServletContext().getRequestDispatcher("Servlet2").forward(req, resp);
    }
}

public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
        Map map = (Map) req.getAttribute("map");

        for (Object o : map.values()) {
            System.out.println(o);
        }
    }
}

如何在它们之间进行重定向?我需要在getRequestDispatcher方法中使用哪个路径?还有一个条件-Servlet2必须在注释或web中没有任何映射。xml


共 (1) 个答案

  1. # 1 楼答案

    Servlet2 must be without any mapping in annotations or in web.xml.

    然后不能使用HttpServletRequest#getRequestDispatcher(String),这是一种容器管理的方法,用于检查这些映射

    这种情况是荒谬的,毫无意义。如果不打算使用Servlet容器,请不要使用Servlet。创建一个执行所需操作的服务类。你不需要把一切都变成Servlet

    唯一(荒谬的)选择是实例化Servlet2并显式调用其doGet方法