Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

model view controller - How to develop JSP/Servlets Web App using MVC pattern?

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. 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.

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

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>

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.

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?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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).

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...