Getting Started With MVC in Java

Introduction

This article explains MVC in JSP. The Netbeans IDE is used for the example. First we discuss MVC and then use an example to briefly illustrate MVC.

What is MVC

MVC stands for Model, View and Controller. The Model is used to access the database, the View controls the front page access and the Controller controls the logic of the programs. In  simple words, it is a design pattern that separates the data, presentation logic and business logic. The Controller is an interface so in the relationship between Model and View, all requests are intercepted. The Model (used to control database access) represents the state of the application, in other words data. The View represents the presentation.

When beginning development of some web apps, we need to know what design models that we need to use. There are two types of programming models (design models). The two architectures are Design 1 and Design 2.

1. Design 1

In this model, we use JSP and a Servlet as the main technologies for developing web applications.

JSP: It overcome nearly all the problems of servlets, it provides a better separation of concerns. Now we can separate business logic and presentation easily. We don't need to redeploy the application if a JSP page is modified. It provides development of a web application with support of the use of custom tags, JavaBeans, and JSTL (Java Server Pages Standard Tag Library) that allows easier debugging and testing of applications.

Servlet: was considered superior to CGI. This technology doesn't create processes, rather it creates a thread to handle the request. The advantage of creating a thread over a process is that it doesn't allocate a separate memory area. Thus many subsequent requests can be easily handled by servlets.

Fig-MVC1.jpg

As we can see in the preceding figure, the flow of the model 1 architecture is as in the following:

  1. A web browser (such a IE, Opera, Crome, etcetera) sends a request for the JSP page.
  2. JSP (Java Server Page) accesses the Java Bean and invokes the business logic.
  3. Java Bean connects to the database and gets/saves the data.
  4. A response is sent to the browser that is generated by JSP.

Advantage

  • This design model is quick and easy to develop using JSP web page.

Disadvantages

They have several disadvantages including:

  • Development is time-consuming.
  • Control over navigation is decentralized.
  • It is hard to extend.

2. Design 2 (MVC) Architecture.

This is based on the MVC (Model, View and Control) design pattern.

  • Model

          Represents the business logic and state (data) of the application.

  • View

           Displays/shows data, in other words it represents the presentation.

  • Controller

          Shows the relationship between the model and the view. It intercepts all the requests, in other words receives input and commands to the Model/View to change accordingly.

Fig-mvc2.png.jpg

Advantages

The following are the advantages of this design pattern:

  • Centralized navigation in this model, which is easy to controll in developing applications.
  • The development of an application is easy.

Disadvantages

  • In this design, we need to write the control code of our project; if we change it then we need to recompile our project to make changes.

Let's see an example to briefly understand the MVC architecture.

In this example, we are using three components as a Servlet to controll the application, JSP is used as a view component and Java Bean is used as a class model.

In this example, we have created 4 pages using the Netbeans IDE 7.4.

The page description is as follows:

  • UserControl.java (provide control).
  • LoginPage.jsp and WelcomeUser.jsp (used as a view components).
  • web.xml (used for mapping the servlet file).

Step 1

Open the Netbeans IDE.

Fig-1.jpg

Step 2

Now click on File menu then select "New Project" as in the following:

Fig-2.jpg

Step 3

Now choose "Java Web" -> "Web application" as in the following:

Fig-3.jpg

Step 4

Now click on "Next" then enter your project name as follows; I entered "MVCproject" there.

Fig-4.jpg

Step 5

Now click on "Next" then choose your server (I used "Apache Tomcat" then click on "Finish" as in the following:

Fig-5.jpg

Step 6

Now you will see that a default "index.jsp" has been created, we need to delete that page and create a new JSP page as follows. Right-click on Web Pages then select "New" -> "JSP" as shown in the following figure.

fig-6.jpg

Step 7

Now a new window is generated asking for a page name; specify "LoginPage" for the file name as in the following:

Fig-7.jpg

Step 8

Now click on Finish. A "LoginPage.jsp" is generated with default coding as in the following:

Fig-8.jpg

Step 9

Now change the code in the "LoginPage.jsp" as in the following:

LoginPage.jsp

<%

if(request.getAttribute("generateerror")!=null)

{

out.print("It is not a valid user!Please Try again with correct name and password<hr>");

}

%>

<form action="UserControl">

User Name:<input type="text" name="username"/><br/>

User Password:<input type="password" name="userpass"/><br/>

<input type="submit" value="login"/>

</form>

Fig-9.jpg

Step 10

Now create another JSP page, "WelcomeUser.jsp", and write the following there:

Welcome User!
You are successfully login.

Create and write it as in the following:

fig-10.jpg

Step 11

Now you need to create a servlet file as in the following.

Right-click on the project then select "New" -> "Servlet" as shown in the following figure.

Fig-11.jpg

Step 12

Now provide your class name in the new window. I provided "UserControl" as shown in the following figure.

Fig-12.jpg

Step 13

Now change the code in "UserControl.java" as in the following:

UserControl.java

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

public class UserControl extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res)

       throws ServletException, IOException

   {

       res.setContentType("text/html");

       PrintWriter output = res.getWriter();

       String name=req.getParameter("username");

       String pass=req.getParameter("userpass");

       if(name==null && pass==null)

       {

              RequestDispatcher reqdisp=req.getRequestDispatcher("LoginPage.jsp");

              reqdisp.forward(req, res);

       }

       else if(name.equals("sandeep") && pass.equals("sandeep"))

       {

              RequestDispatcher reqdisp=req.getRequestDispatcher("WelcomeUser.jsp");

              reqdisp.forward(req, res);

       }

       else

       {

              req.setAttribute("generateerror","true");

              RequestDispatcher reqdisp=req.getRequestDispatcher("LoginPage.jsp");

              reqdisp.forward(req, res);

       }

       output.close();

       }

}

fig-13.jpg

Step 14

Now you don't need to develop a web.xml page in Netbeans, it is generated by default. If you want to see this file then follow this procedure.

Go to your project then left-click on the Web Pages folder then click on the "WEB-INF" folder. Then click on the Web.xml file. You will see the following code there.

Web.xml

Fig-14.jpg

Step 15

Now our project is ready to run. To start running the project follow this path:

Right-click on the "LoginPage.jsp" file (that is in the Web Pages folder) then choose "Run File" as in the following:

fig-15.jpg

Step 16

Now a window is generated in your default web browser that contains the following information.

fig-16.jpg

Step 17

Now there were the two text boxes User Name and User password. Now check there with the following condition. I provide a default User Name and Password as "sandeep"; when I typed that in then it will move to the next page, the "WelcomeUser.jsp" page. Otherwise it generates an error message. Now check for the following conditions.

1. When the name and password are both null.

This condition shows an error message as in the following:

fig-17.jpg

2. When the name is correct but the password is not.

fig-18.jpg

When we click on submit, it shows the following error message:

fig-19.jpg

3. When both of the information are correct.

fig-20.jpg

After clicking on the submit button.

fig-21.jpg

Thanks for reading. Hope you might have enjoyed it. In my next article I use some complex applications on MVC to briefly understand the concept of MVC (Model, View and Controller).

Up Next
    Ebook Download
    View all
    Learn
    View all