サーブレットをコントローラー層として使用し、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に移動すると、サーブレットにヒットし、alternate.jsp にディスパッチする場所に到達し、サーブレットを再度実行しますが、これはtime は「example」に等しい pathInfo ではなく、「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>