Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Design Patterns: Implementing Model View Controller in the Java EE Platform

See in this article what the design pattern Model View Controller is and how we can implement it in the new Java EE 7 platform using APIs that facilitate the implementation of the design pattern.

MVC design pattern (Model View Controller) is currently one of the most present design patterns in application development. This is built on the philosophy of "separation of concepts" and in the "data processing encapsulation" of the application from the data provided by the presentation layer. As the authors of the book "Core J2EE Design Patterns" noted, if that process information from the presentation layer is not encapsulated, there is a high probability of creating a system with a high coupling and difficult maintenance and extension.

The separation of concepts that the MVC pattern provides to designers and developers allows the changes made in both the business layer and the user interface to be much simpler and independent.

Developers of Web applications are the ones who use and benefit from the MVC design pattern, but that does not mean that it is only restricted to this type of application.

In the rest of the article we will see what the standard of MCV project is, how we implement it as a POJO and how it is implemented in the new Java EE 7 platform.

If you're interested in learning more about MVC not only in Java, but other platforms, please refer some of our contents:

MVC Pattern

When MVC design pattern is being studied, it is interesting to know what each layer means and what it contains.

The Model layer has the application information and related business logic. It can be represented by an object or a complex graph of related objects. In Java EE applications, information is encapsulated in the frequently deployed domain objects on the application server via an EJB module.

Information needs to be transported between the layers. For this we use the DTO (Data Transfer Object). For example, to transport the data to be stored in a database, we can use a DTO containing this information, then we access the database access layer through the DTO that contains the data, after which the data can be stored in the database.

The View layer is the visual representation of the information contained in the layer that we saw earlier in the Model layer. A subset of the model is represented in a single view. Thus, the view serves as a filter for the information contained in the model. That way, the user interacts with the model information via a visual representation of the View. In addition, the user relies on the business logic which in turn acts upon the data model.

The other layer is the Controller, which is responsible for connecting the previous two layers, i.e., the controller connects to the model view and directs the application flow. This allows you to choose which view will be displayed to the user in response to user input and the business logic that will be processed upon that input. Thus, the controller receives a message from view, which in turn forwards to the Model. The Model prepares a response and sends it back to the Controller that choose the appropriate view and sends it to the user.

MVC pattern covers the client and the intermediate layer of a multilayer architecture. In a Java EE environment, the Model is located in the business layer, usually in the form of a EJB module (Enterprise JavaBeans). Therefore, in business applications we use an EJB to implement the Model.

Controller and View are located on the Web tier. The View is usually built using JavaServer Faces (JSF), JavaServer Pages (JSP) or using frameworks like Primefaces.

The Controller is usually a Servlet receiving requests of Hypertext Transfer Protocol (HTTP) type from the user.

The MVC design pattern can also be combined with other patterns such as the Command, Strategy, Composite and Observer patterns.

There are different ways to implement the MVC design pattern. The two most cited in the current literature and more used in enterprise environments are discussed below:

  • MVC Type I: Such an approach is centered on the page, where the view and the controller exist as an entity referred to as View-Controller, i.e., they are connected. In this approach, the Controller logic is implemented within the View, in the same way it occurs in JSF. All tasks the Controller performs, including the recovery of HTTP request parameters and attributes, as well as the invoke of the business layer and the management of the HTTP sessions, are built into the View using scriptlets and tag libraries. This type engages the generation of the View with the application flow, making maintenance quite complicated. It also overloads the View with features that could be decoupled.
  • MVC Type II: In this type of MVC model, the maintenance problems found in Type I are solved by moving the Controller logic out of the View, placing it in a Servlet. Thus, JSF is concerned only with the presentation of the data to the View.

The main difference between Type I and Type II is where the Controller logic is located. In Type I it is in the View and in the Type II it is separated from the View as a Servlet.

MVC Type II is implemented by various frameworks like Spring MVC, Struts, Grails and Wicket.

Implementing MVC in Pure Code (POJO)

MVC pattern can be implemented using the Java Web technologies. Through this implementation, it is determined where to redirect the user based on the user request. This also helps to keep the sole responsibility of the Controller.

Let's get started setting up the Controller. The Controller we're going to implement responds to any HTTP GET request made in the /users/* path. The mapping of this relationship is defined in the web.xml file as shown in Listing 1.

Listing 1. Example web.xml implementation defining the application Controller.

<servlet>
	   <servlet-name>FrontController</servlet-name>
	   <servlet-class>com.mrbool.mvc.pojo.FrontController</servlet-class>
</servlet>
<servlet-mapping>
	   <servlet-name>FrontController</servlet-name>
	   <url-pattern>/users/*</url-pattern>
</servlet-mapping>

In this code we map the Controller class that is located in com.mrbool.mvc.pojo.FrontController to any requests made through the URL "/users/*". Therefore, every request made to this URL is redirected to the FrontController class that will do the initial processing of the request.

As the Java EE 7 platform supports the new specification Servlets 3.0, we can simply note the Controller class with @WebServlet({"/users/*"}), eliminating the use of the web.xml file.

When such requests are made, doGet() method is invoked in the Servlet. In the example in Listing 2, we have a sample implementation of the Controller. In this code, the Action object is returned from AbstractActionFactory that determines the location of the View which must be returned to the user.

Listing 2. Implementing a Controller.

package com.mrbool.mvc.pojo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FrontController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Action action = AbstractActionFactory.getInstance().getAction(request);
		String view = action.execute(request, response);

		// call the view passing the received request and response as parameters
		getServletContext().getRequestDispatcher(view).forward(request, response);
	}
}

In the example, we have the AbstractActionFactory that creates an instance of the class ActionFactory. The getAction() method accepts a HttpServletRequest object that contains a reference to the URI of the requested location. The factory uses the URI to determine which Action object return to the Controller.

Listing 3 shows an example of the AbstractActionFactory class and of the ActionFactory class. It can be seen that there is a mapping of URI requests paths and Action objects in the Map action. An Action object is chosen from the map based on the request URI and returned to the Controller.

Listing 3. Implementation of the factories.

package com.mrbool.mvc.pojo;

public class AbstractActionFactory {

	private final static ActionFactory actionFactory = new ActionFactory();

	// Returns an instance unique of the ActionFactory
	public static ActionFactory getInstance() {
		return actionFactory;
	}
}

package com.mrbool.mvc.pojo;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

public class ActionFactory {
	private Map <String, Action> actions = new HashMap<>();
	private Action action;

	public ActionFactory() {
		actions.put("GET/users", new HomeAction());
		actions.put("GET/users/listusers", new UsersListAction());
	}

	public synchronized Action getAction(HttpServletRequest request) {
		String path = request.getServletPath() + request.getPathInfo();

		String actionKey = request.getMethod() + path;

		System.out.println(actionKey);

		action = actions.get(actionKey);

		if (action == null) {
			action = actions.get("GET/users");
		}
		return action;
	}
}

The concrete implementation of Action must provide an implementation for the execute() method. This method is responsible for performing the necessary business logic to generate the page the user requested. Among other things, it can perform a database query to obtain information, perform calculations or generate a file.

In Listing 4 code, we have the implementation of this method that builds a list of users who are added as an attribute to the request object. After that, it returns the location of the View to be displayed to the user. The information now stored in the request object is accessed by listuser.jsp page and then displayed.

Listing 4. Example of an Action class.

package br.com.devmedia.mvc.pojo;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UsersListAction implements Action {
	public String execute(HttpServletRequest request, HttpServletResponse response) {
		// Normally, these data is catched from an EJB module that searches the information in the database
		List <String> userList = new ArrayList<> ();

		userList.add("Wander Wildner");
		userList.add("Carl Gerbase");
		userList.add("Jennifer Tomphson");
		userList.add("Harold Heinz");

		request.setAttribute("userList", userList);

		return "/WEB-INF/pages/listuser.jsp";
	}
}

The Action object returns to the Controller, which receives the page location to which it must send the request and response objects as shown in the following example, which has been shown previously in the Controller code:

String view = action.execute(request, response);
getServletContext().getRequestDispatcher(view).forward(request, response);

In the example in Listing 5, we have a JSP page that accesses the requestScope variable and returns the "userList" list created in UsersListAction. After that, there will be an iteration over the collection, displaying the names.

Listing 5. Example of listuser.jsp implementation page that was requested by the user.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title>Users List</title>
	</head>
	<body>
		<h1> User of our favorite band are: </h1 >
		<c:forEach items="${requestScope.userList}" var="user" >
			<br> ${user}
		</c:forEach >
	</body>
</html>

This example showed how you can create an implementation of the MVC pattern. In the next section, we will show how to implement this same application using the advantages of the Java EE 7 platform.

Implementing MVC in Java EE 7 Platform

As seen previously, using pojos we had to write the logic of the Controller, the mapping of URLs to the Controller classes, and write a lot of code to the full implementation of MVC. But the Java EE platform has greatly simplified the implementation of the MVC pattern. So we just need to focus our efforts on the View and the Model. The FacesServlet takes care of the implementation of the Controller for developers. In the following sections we'll talk a bit more about FacesServlet.

FacesServlet

The FacesServlet takes care of the management of user requests and delivers the view to the user, as well as our Controller implemented earlier. It manages the lifecycle of the applications that use JSF to build the user interface. All user requests pass through FacesServlet.

Now, let's illustrate how to make a MVC using FacesServlet and JSF. Importantly, the declaration view of language for JSF is called facelets. The facelets are substitutes for JSPs and are written in XHTML using CSS (Cascading Style Sheets).

JSFincludes the concept of backing beans. These are POJOs (Plain Old Java Objects) annotated with @Named and @RequestScope, prior to the Java EE platform 7 where they were annotated with @ManagedBean. These beans are accessible through a JSF page for the duration of the HTTP request, but the type of scope can be changed. However, it is best studied in specific JSF articles. We can refer to these methods directly into JSF.

In Listing 6 code, we rewrite the UserListAction class using the backing bean.

Listing 6. UserListAction class rewritten as a backing bean

package com.devchronicles.mvc.javaee;

import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@RequestScoped
@Named
public class UserListAction {
	private List<String> userList = new ArrayList<>();

	public List<String> getUserList() {
		return userList;
	}

	public String execute() {
		userList.add("Wander Wildner");
		userList.add("Carl Gerbase");
		userList.add("Jennifer Tomphson");
		userList.add("Harold Heinz");
		
		return "/WEB-INF/pages/listuser.xhtml";
	}
}

Next step is to create a index.xhtml file that is the starting point of the user contact with our application. This file replaces home.jsp and is called directly by the browser. The purpose of this JSF is to call the execute() method in UserListAction preparing the information for the View listuser.xhtml.

Listing 7 code shows how this method is called.

Listing 7. Example of a page to the MVC pattern.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
  <h:head>
      <title>Welcome</title>
  </h:head>

  <h:body>
      <h1>Interact with out app below</h1>

      <h:form>
          <h2>Click here to see a <h:commandLink value="List of Users" action="#{userListAction.execute}"/>.</h2>
      </h:form>
  </h:body>
</html>

We use the tag h:commandLink,reference the backing bean and the execute() method in the action element. The execute() method is called directly by JSF. This generates a list of users, returns the location of the view that displays the list, and finally invokes the getUserList() method displaying the list of users.

Listing 8 shows the information returned to the user.

Listing 8. View that displays the Model information.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html">

  <head>
      <title>Users List</title>
  </head>

  <body>
      <h1>The users of our favorite band are:</h1>
      <ui:repeat value="#{userListAction.userList}" var="user">
          <h:outputText value="#{user}" />
          <br/>
      </ui:repeat>
  </body>

</html>

When we deploy the application, the View index.xhtml displays the link, which when clicked displays the list of users as follows:

Users of our favorite band are:

Wander Wildner

Carl Gerbase

Jennifer Tomphson

Harold Heinz

Conclusion

Only this is required to build an application using the Java EE Platform 7. This greatly reduces the effort of the developers in standard features that can be solved by such a robust platform as the Java EE 7, saving the developer time that can be used to focus on application business logic.

Bibliography

[1] Erich Gamma, Ricard Helm, Ralph Johnson, John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1994).

[2] Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra. Head First Design Patterns. O'Reilly Media, 2004.

[3] Deepak, A.; Dan, M.; John, C.; Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition). Prentice Hall, 2003.



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login