【问题标题】:Forward to a servlet from another servlet or from a filter从另一个 servlet 或从过滤器转发到一个 servlet
【发布时间】:2017-04-03 04:00:00
【问题描述】:

通常我会从 servlet 转发到 jsp 或映射的 URL,互联网上到处都是这样的例子。但我需要将请求转发给内部 servlet。例如,通过使用其完整的类名,而不将该 servlet 映射到 URL。如何将请求从另一个 servlet 或过滤器转发到内部 servlet?

【问题讨论】:

  • 我怀疑你可以使用任何 servlet 而不将其映射到 url。可以做的最简单的事情是使用 @WebServlet 注释而不是在部署描述符中映射它。

标签: jsp servlets servlet-filters


【解决方案1】:

正如 Shadab 所说,我认为您应该使用 @WebServlet 注释(和 RequestDispatcher),例如:

@WebServlet(urlPatterns = { "/sample" })
public class SampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    RequestDispatcher dispatch = req.getRequestDispatcher( "/forwardpath");
    dispatch.forward(req, res);
}

SampleServlet -> ForwardedServlet

@WebServlet(urlPatterns = { "/forwardpath" })
public class ForwardedServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ...
}

【讨论】:

    【解决方案2】:

    您想要的方法是 RequestDispatcher getNamedDispatcher(String name);,它返回一个 RequestDispatcher 对象,该对象充当命名 servlet 的包装器。

    ServletConfig.getServletName() 的 javadoc 说:

    名称可以通过服务器管理提供,在 Web 应用程序部署描述符中分配,或者对于未注册(因此未命名)的 servlet 实例,它将是 servlet 的类名。

    你只需要做:

    getServletContext().getNamedDispatcher("full.class.name.for.new.servlet");
    

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 2012-08-28
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      相关资源
      最近更新 更多