我正在尝试将 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,但这time 而不是 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>