如何使用MVC模式开发JSP/Servlets Web App?

问题描述:

我正在开发一个JSP/Servlet Web应用程序(没有框架).我想使用 MVC 模式.我将像这样设计我的项目:

I'm developing a JSP/Servlet web app (no frameworks). I want to use MVC pattern. I am going to design my project like this:

  1. 控制器:读取请求,提取值,与模型对象进行通信并将信息提供给JSP页面的servlet.
  2. 查看:JSP页面.
  3. 模型:Java类/Java Bean等.
  1. Controller: a servlet that reads a request, extracts the values,communicates with model objects and gives information to a JSP page.
  2. View: JSP Pages.
  3. Model: Java Classes / Java Beans .. etc.

问题:Index.jsp是我网站上的起点(默认页面).因此,Index.jsp成为分析请求的控制器.例如,以下请求:

The problem: Index.jsp is the starting point (default page) in my web site. So, the Index.jsp becomes the controller to parse the request. For example, the following request:

index.jsp?section=article&id=10

在index.jsp中的解析如下:

is parsed in index.jsp as following :

<div class="midcol">
<!-- Which section? -->
<%String fileName = request.getParameter("section");
if (fileName == null) {
fileName = "WEB-INF/jspf/frontpage.jsp";
} else {
fileName = "WEB-INF/jspf/" + fileName + ".jsp";
}
%>
<jsp:include page='<%= fileName%>' />
</div>

在这里,我不能强迫servlet作为控制器,因为index.jsp在这里是控制器,因为它是起点.

Here, I can't force the servlet to be a controller, because the index.jsp is the controller here since it's the starting point.

有什么解决方案可以将请求从index.jsp转发到servlet,然后再返回到index.jsp?还是实现 MVC 目标的任何解决方案-servlet应该是控制器?

Is there any solution to forward the request from index.jsp to the servlet and then go back to index.jsp? Or any solution that achieves the MVC goal - the servlet should be the controller?

我正在考虑将 FrontPageController servlet 作为默认页面而不是 index.jsp ,但是我不知道这是一个理想的主意吗?

I'm thinking of making a FrontPageController servlet as default page instead of index.jsp, but I don't know if it's a perfect idea?

摆脱index.jsp,只让控制器servlet监听特定的感兴趣的url-pattern.控制器本身应使用RequestDispatcher将请求转发到感兴趣的JSP页面.

Get rid of index.jsp and just let the controller servlet listen on a specific url-pattern of interest. The controller itself should forward the request to the JSP page of interest using RequestDispatcher.

request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

或者,您可以让index.jsp转发或重定向到控制器servlet覆盖的URL,该URL依次显示默认"页面(似乎是frontpage.jsp).

Alternatively you can let index.jsp forward or redirect to an URL which is covered by the controller servlet which in turn shows the "default" page (which seems to be frontpage.jsp).

也就是说,在正确的MVC方法中,您应该在JSP文件中使用 scriptlet .每当您需要在JSP文件中编写一些原始Java代码,而这些代码不能被taglibs(

That said, in a correct MVC approach, you should have no scriptlets in JSP files. Whenever you need to write some raw Java code inside a JSP file which can't be replaced reasonably by taglibs (JSTL and so on) or EL, then the particular Java code belongs in any way in a real Java class, like a Servlet, Filter, Javabean, etcetera.

关于本地MVC方法,您可能会找到此答案这篇文章也很有用.

With regard to the homegrown MVC approach, you may find this answer and this article useful as well.