【发布时间】: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