Servlets JSP MVC Struts
Servlets JSP MVC Struts
Servlets JSP MVC Struts
(Part I)
Venkat Subramaniam
venkats@agiledeveloper.com
http://www.agiledeveloper.com/download.aspx
Abstract
Servlets and JSPs bring significant advantage to web development, yet come with
significant limitations. In this article, we discuss what’s fundamentally wrong with
servlets and JSPs, discuss the Model 1 and the MVC based Model 2 architecture, and
introduce the benefits of using a framework like Struts.
if (session.isNew())
{
target = (int)(Math.random() * 100);
out.println("Welcome to Guessing Game");
session.setAttribute("target", "" + target);
session.setAttribute("attempts", "1");
}
else
{
target = Integer.parseInt(
session.getAttribute("target").toString());
attempts =
Integer.parseInt(
session.getAttribute("attempts").toString());
attempts++;
session.setAttribute("attempts", "" + attempts);
guess = Integer.parseInt(request.getParameter("guess"));
}
%>
Number of attempts <%= attempts %>
<BR>
<%
if (guess == target)
{
out.println(
"Congratulations! you got it. Lets start a new game!");
target = (int)(Math.random() * 100);
session.setAttribute("target", "" + target);
session.setAttribute("attempts", "1");
}
else
{
if (guess < target)
out.println("Aim higher");
else
out.println("Aim lower");
}
%>
<BR>
<FORM action="http:Guess.jsp" method="POST" >
Enter your guess:
<INPUT id="guessInput" type="text" name="guess"/>
<INPUT type="submit" value="Send"/>
</FORM>
<SCRIPT>
document.all.guessInput.focus();
</SCRIPT>
If it is a new session (new game) we create a target (that the user is going to guess) and
store it in the session along with an initial value for number of attempts. If this is not a
new session (i.e., it is a continuing game), then we fetch the target and number of
attempts from the session. We check to see if the user’s guess is equal to the target. If so,
we congratulate the user and reset the variables to start a new game. Otherwise, we
instruct the user to guess again.
Model 1 Architecture
Servlets are great for Java code. JSPs are great for HTML. Placing HTML into servlets or
placing Java code in JSP leads to a system that is very hard to maintain. This brings us to
the so called Model 1 architecture shown below:
Figure 1. Model I Architecture
In Model 1 architecture, a series of JSP pages (or servlets) do all the work. Each page
takes upon the complete task of fulfilling a request. There is no separation of concern.
This leads to code that is very hard to maintain. It takes some effort to keep the different
aspects of the code separated from each other.
In this architecture, the request from the browser is received by a servlet. The servlet
(which houses Java code) communicates with simple Java objects to access information
and takes care of processing. Once the request has been processed, the flow of control is
transferred to an appropriate JSP page. The JSP page, which will contain HTML for most
part and some limited JSP tags will then display the information by accessing the simple
Java objects and some session variables, if need be.
Before we start looking at the code, let us take a look at this application under execution:
This has got to be a better implementation because I was able to guess the number in
fewer tries! I would like to point to some thing important to note. From in the address
bar, you can see that the visits are going to one of two servlets (Guess and GuessAction)
and not to a JSP page. Ideally, a user should never have to visit a JSP page directly.
The request goes to the servlet directly. The servlet takes care of the actual processing of
the request and then transfers the control to an appropriate JSP page. The JSP page then
will display the response to the user. The subsequent request (after the user fills in the
form and clicks the submit button) is directed to a servlet again for processing. A user of
the system should not be aware of the existence of any JSP pages at all. Let’s take a
look at the actual code now.
request.getRequestDispatcher("/start.jsp").
forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
{
doGet(request, response);
}
}
The servlet first initializes the target, sets session variables and transfers control to the
start.jsp page. The class Guessing.Info is a simple bean that holds two properties attempts
and message as shown below:
// Info.java bean
package Guessing;
The GuessRequest.htm contains the form for the user to fill in as shown below:
<!-- GuessRequest.htm -->
<FORM action="http:GuessAction" method="POST">
Enter your guess:
<INPUT id="guessInput" type="text" name="guess"/>
<INPUT type="submit" value="Send"/>
</FORM>
<SCRIPT>document.all.guessInput.focus();</SCRIPT>
The reason for including GuessRequest.htm in the start.jsp page will become obvious
soon as you find that the same form is needed in another jsp page as well.
Note that the form (in GuessRequest.htm) directs the user to the servlet GuessAction. The
GuessAction servlet is shown below:
//GuessAction.java servlet
import javax.servlet.*;
import javax.servlet.http.*;
import Guessing.Info;
if (guess == target)
{
forwardPage = "/GameOver.jsp";
message = "Congratulations!";
}
else
{
if (guess < target)
message = "Aim higher!";
else
message = "Aim lower!";
}
info.setMessage(message);
request.getRequestDispatcher(forwardPage).
forward(request, response);
}
The GuessAction servlet checks if the user’s guess is correct. If the guess is lower (or
higher) than the target, it sets a message (in the info bean which resides in the session) to
“Aim higher” (or “Aim lower”). Then the control is transferred to the
ContinueGuessing.jsp. If the user’s guess is correct, then the control is transferred to the
GameOver.jsp.
From the JSP pages we can see that there is no java code in them. It uses regular HTML
and the JSP tag libraries. Any web designer (by which I mean one who is not a Java
programmer) will be able to maintain it. They can modify it, change the fonts, add
pictures and change the esthetics of the page to their hearts content. Notice also that the
servlets do not have any HTML in them. Java programmers (by which I mean one who is
not interested or capable in the esthetics of the presentation) can modify the code, access
any database, create as much or as little Java code to their hearts content as well. This has
given a good separation of concern.
Conclusion
In this article we presented an example of a simple application which suffers from the
mixing of HTML and Java code (presentation and logic). We then showed how we
managed to achieve the separation of concerns and work towards an implementation that
follows the MVC architecture. In the next issue we will see how this can be implemented
more elegantly using Struts.
References
1. http://jakarta.apache.org/tomcat/index.html.
2. The Unified Software Development Process, Jacobson, Booch, Rumbaugh,
Addison-Wesley.