【问题标题】:How to redirect from one servlet to another by using tricky redirection?如何使用棘手的重定向从一个 servlet 重定向到另一个?
【发布时间】:2014-01-06 20:33:28
【问题描述】:

如果我有两个 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 中没有任何映射。

【问题讨论】:

  • 映射对于 servlet 是强制性的...
  • 但我需要对用户不可见的 Servlet2。它无法从浏览器访问。如果我使用映射用户可以访问 servlet。
  • 您确定要 Servlet 而不是 JSP(这是一种 servlet,不会在 web.xml 中设置任何注释或地址)吗?
  • 太糟糕了,因为通过将您的 JSP 放在 WEB-INF/yourJspFile.jsp 中,您可以通过请求调度程序向它发送请求。它还会从浏览器中隐藏这个 JSP“地址”。

标签: java servlets redirect requestdispatcher


【解决方案1】:

Servlet2 必须在注解或 web.xml 中没有任何映射。

那么你就不能使用HttpServletRequest#getRequestDispatcher(String),这是一个检查这些映射的容器管理方法。

这种情况很荒谬,毫无意义。如果您不打算使用 Servlet 容器,请不要创建 Servlet。创建一个执行您需要的操作的服务类。您无需将所有内容都设为Servlet

您唯一(可笑)的替代方法是实例化 Servlet2 并显式调用其 doGet 方法。

【讨论】:

  • 如果我需要在 Servlet2 中使用映射,那么也许我可以使用 Filter 来切断对 Servlet2 的所有可能请求?
  • @user3163426 你想用Servlet2做什么?为什么需要HttpServlet
  • 这只是一种练习。在 Servlet2 中,我打印了一张地图。就是这样:)
  • @user3163426 你可以和Servlet1一起练习。如果Servlet2 不打算用作Servlet,请不要将其设为Servlet
  • @user3163426 你可能认为你有,但实际上你没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 2020-04-23
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多