Model View Controller (MVC)

Pervious relative links:

In present trend it is very important to reuse the

  1. Html code should not be hardcoded in servlet, because of maintenance problem and there is no reusability.
  2. Connection creation is not the responsibility of servlet. So the connection code must be moved out from servlet.
  3. Servlet should not contain any queries/statements related to database.
  4. If servlets contains code for UI or database communication or business logic, we end up in maintenance nightmare as we move on and enhancing the functionality.

Here we try to say that every class should have single responisblity, so servelts are meant for controling the flow not for other purpose. So, the solution to the above problems is ‘Model View Controller design pattern’.

Model View Controller (MVC):

Model View Controller design pattern is most popular pattern for developing web application s. This is mainly used to bring the single responsibility between the classes, so that application code can be well maintained and loosely coupled with view, business logic and flow.

Model:

Model is responsible for having business logic and data. It can have code for executing busines logics and it can interact with database to get data. Model don't know anything about view. In general model can be POJO classes , service classes.

View:

View is meant for user interface i.e. presetation and is responsible for presentating the data given by model. In general view can be html or jsp. View knows about datausing which it should create presentation, but model don't know about view, because view can be anything, but data won't change. For instance view can be mobile or browser, etc... but model is same :).

Controller:

Main responsibility of the controller is to control the request and response. It knows which model and view is suitable for handling the request. In general servlets are the controllers in web applications.

Let’s explain this mvc pattern with an example.

Let’s take the application of result. When we enter the hall ticket number, it should validate the hall ticket number and then it should give appropriate result to given number.

The flow is as follows:

  1. User enters hall ticket number in "ResultRequest.html"
  2. The appropriate servlet acts i.e. "ResultServlet.java"
  3. Then the appropriate method “getResult()” of “ResultService” class is called in ResultServlet.java .This getResult() takes the help of an helper class called “EntityManagerProvider.java” to establish the database connection.
  4. Then the validation of hall ticket number is done in the method and the appropriate result is given to the servlet class.
  5. The servlet class then calls the appropriate jsp page to make view the result to the user.

In our application the different classes we have are:
  1. ResultService.java which comes under model.
  2. Result.jsp and ResultRequest.html which comes under view.
  3. ResultServlet.java which comes under controller.
  4. We have another class called EntityManagerProvider.java which is a helper class which provides DBconnection.
  5. Number of database connection creations should be as minimal as possible as it is a heavy object. If you want more than one connection, then go for connection pooling.
  6. We have another class called Result.java which is a pojo class that is similar to the table maintained in the database. The fields of pojo class and table in the database should be same. The pojo represents the table in the database.
The program is as below:
		
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> < html> <head> <metahttp-equiv ="Content-Type"content="text/html; charset=ISO-8859-1"> <title>Result </title> </head> <body> <formmethod ="post"name="result" action="/result/ResultServlet"> <TABLEalign ="center"vlign="center"> <TR> <TDwidth ="30%"class="tdLabelRightAlign"> <fontcolor="red">* </font> HTN:  </TD> <TDwidth ="70%"class="tdLabelLeftAlign"> <inputtype ="text"name="htn" size="19"> </TD> </TR> </TABLE> <inputtype ="submit"class="button70" value="Submit" name="B1"> </form> </body> </html>
Then the appropriate servlet for this html page is ResultServlet.java:
		
package com.gk.servlet; import com.gk.model.service.ResultService; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.*; publicclassResultServletextends HttpServlet { public ResultServlet() { } protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String htn = req.getParameter("htn"); ResultService rs = new ResultService(); com.gk.pojo.Result result = rs.getResult(htn); req.setAttribute("result", result); RequestDispatcher rd = req.getRequestDispatcher("/result.jsp"); rd.forward(req, resp); } }

The controller/servlet only controls the request-response flow.

ResultService.java:
		
package com.gk.model.service; import javax.persistence.EntityManager; import com.gk.connectionprovider.EntityManagerProvider; import com.gk.pojo.Result; public class ResultService { public ResultService() { } public Result getResult(String htn) { EntityManager entityManager = EntityManagerProvider.getSession(); Result result2 = (Result)entityManager.find(Result.class, Integer.valueOf (Integer.parseInt(htn))); return result2; } }

Another class called Result.java is maintained(which is a pojo class is also a helper class):

		
package com.gk.pojo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Result { @Id @GeneratedValue Private int htn; private String name; private int m1; private int m2; public Result() { } public void setName(String string) { name = string; } public void setM1(int m1) { this.m1 = m1; } public void setM2(int m2) { this.m2 = m2; } public int getHtn() { return htn; } public String getName() { return name; } public int getM1() { return m1; } public int getM2() { return m2; } }

Here we use another helper class called EntityManagerProvider.java:

		
Package com.gk.connectionprovider; Import java.util.HashMap; Import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.Ejb3Configuration; public class EntityManagerProvider { private static EntityManagerFactory managerFactory; private EntityManagerProvider() { } public static EntityManager getSession() { if(managerFactory == null) { Ejb3Configuration cfg = newEjb3Configuration(); MapconfigOverrides = new HashMap(); configOverrides.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); configOverrides.put("javax.persistence.jdbc.user", "root"); configOverrides.put("javax.persistence.jdbc.password", "root"); configOverrides.put("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/result"); Ejb3Configuration configured = cfg.configure("result", configOverrides); try { managerFactory = configured.buildEntityManagerFactory(); }catch(RuntimeExceptionrte){ rte.printStackTrace(); throwrte; } } return managerFactory.createEntityManager(); } }

Then finally the retrieved data is sent to the jsp page i.e (view) Result.jsp:

		
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@pageimport="com.gk.pojo.Result"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% Result r = (Result)request.getAttribute("result");%> <table> <thead> <tr> <td>htn</td> <td>name</td> <td>m1</td> <td>m2</td> </tr> </thead> <tr> <td><%=r.getHtn() %></td> <td><%=r.getName() %></td> <td><%=r.getM1() %></td> <td><%= r.getM2() %></td> </tr> </table> </body> </html>

The output is:

This is the ResultRequest.html

mvc request result

Enter the hall ticket number and then click on submit.

fill HTNO

The result is:

result of mvc
HTML Comment Box is loading comments...