【问题标题】:Using Servlets and JSP together resulting in unexpected looping一起使用 Servlet 和 JSP 会导致意外循环
【发布时间】:2010-11-04 23:53:12
【问题描述】:

我正在尝试将 Servlet 用作控制器层,将 JSP 用作视图层。我读过的许多示例/教程都建议这样做:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // add something for the JSP to work on
    request.setAttribute("key", "value");

    // show JSP
    request.getRequestDispatcher("main.jsp")forward(request, response);
}

这对于简单的例子来说很好,但是当我加强它时(甚至一点点):

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // add something for the JSP to work on
    request.setAttribute("key", "value");

    String pathInfo = request.getPathInfo();
    if ((pathInfo != null) && (pathInfo.length() > 1)) {
        // get everything after the '/'
        pathInfo = pathInfo.subSequence(1, pathInfo.length()).toString();

        if (pathInfo.equals("example")) {
            request.getRequestDispatcher("alternate.jsp").forward(request, response);
        }
    }

    // show JSP
    request.getRequestDispatcher("main.jsp").forward(request, response);
}

据我所知,如果我转到(例如)http://localhost/main/example,它会访问 servlet,到达它分派到alternate.jsp 的位置,然后它会再次运行 servlet,但这次不是pathInfo 等于“example”,它等于“alternate.jsp”,所以它通过 main.jsp 调度。

我怎样才能让它运行不同的 JSP 文件,其中的一些逻辑类似于上面?

为了更好地衡量 web.xml 中的映射是:

<servlet>
    <servlet-name>Main</servlet-name>
    <servlet-class>com.example.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Main</servlet-name>
    <url-pattern>/main/*</url-pattern>
</servlet-mapping>

【问题讨论】:

  • 嗯...我想我必须大量修改这个问题才能得到我需要的答案。
  • 好的,在进一步缩小问题范围并尝试更多测试后,我提出了一个更好的问题。 stackoverflow.com/questions/1030302/…

标签: java jsp servlets web.xml wildcard-mapping


【解决方案1】:

奇怪的是,我只是从另一个角度看待这个问题。有关匹配顺序的信息,请参阅here,第 7.3.2 节 Servlet 匹配过程。

简短的总结:基于路径的映射胜过基于扩展的映射,所以你在劫持 JSP 映射。

【讨论】:

  • 有人对替代方法有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
相关资源
最近更新 更多