MVC in J2EE


MVC
MVC is a architectural design pattern that can be used not only for J2EE but also for any other programming models or languages. It is widely using in software design as a general design solution for problem solving. Here I have used this pattern to create J2EE application that makes easier and enhances re-usability, understadability and plug in demand factors in advance. This makes developers and other code reviewers easier to understand where the business logic go on and where presentation tier goes on and

MVC stands for Model View Controller ;

Model- contains data and provides methods to access them, eg: database model java classes, where you code java jdbc connectivity and sql query execution methods. You invoke them when request is reached to your controller servlets which will be described later. In addition to plain java classes for database handling side, you can implement model by using entity beans and session beans which I am not going to cover in this session. I will explain how to build model through simple java classes which is not biased to beans. Model basically has two responsibilities;
(01). Respond to controller requests (Servlet)
(02). Respond to viewer requests and notifies view when model changes (db data changes)

View- duty of view is to let users see model in an appropriate way. Then users can make changes what ever they need in view that affects model to be changed accordingly. A view point has usually a one to one correspondence witha display surface and knows how to render to it. JSP or JSF acts as a view in J2EE.

Controller- acts as an interface between view and model. It takes requests from view and hands them over to model so that model can store them or retrieve them or update them or delete them. So basically this is named as a servlet, special kind of java class that has inbuilt methods such as doPost, doGet and etc. So technically controller servlet communicates with JSP (front tier) and loads the HttpServletRequest or HttpSession with relevant data before forwarding the HttpServletRequest and Response to the JSP using a RequestDispather.

Below statement simply states about MVC which I have extracted from wikipedia;
"An MVC application may be a collection of model/view/controller triads, each responsible for a different UI element. The SwingGUI system, for example, models almost all interface components as individual MVC systems.
MVC is often seen in web applications where the view is the HTML or XHTML (JSP) generated by the app. The controller receives GET or POST input and decides what to do with it (Servlet), handing over to domain objects (i.e. the model) that contain the business rules and know how to carry out specific tasks such as processing a new subscription, and which hand control to (X)HTML-generating components such as templating engines, XML pipelines, Ajax callbacks, etc."

I have specified this fragment because it clearly confirms what I have posted above.

Now we better move for practical implementation of MVC using J2EE. I have used JSP as a View, Servlet as a Controller and java clas as a Model for implementation. In future I will explain MVC using same scenario based on EJB's Entity beans and Sessions beans. But now I have used jsp/servlet only which is very simple way to show this.


Above diagram shows the way of flow takes place.

Scenario:
You are asked to design a J2EE solution for a ABC company. It is a trading company which allows its customers to register in website and having logged in after successful completion of registration process, each customer can purchase stuff, vote, comment and shopping by adding things into cart while checking amount he/she has so far added in to cart and etc. So now you have to implement web based solution for this registration and log in functionalities. Registration screen contains users first name, last name, NID, email, password for the purpose of logging to ABC company, country and DOB

You can use either php or jsp, but here since I am so far suggesting you about jsp/servlet based solutions using MVC, I am going to show you how this can be archived using J2EE MVC pattern in eclipse IDE with MySQL data base .

(01) In Eclipse create dynamic web project.
Create a JSP page under your project


@ page import="java.sql.ResultSet"%>
@ page import="DBCore.HandleDB"%>
@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Registration
First Name
Last Name
Password
Retype Password
Email
Date of Birth
Country
I confirm that above details provided areaccurate according to the nest of my knowledge
Then in
you call "HandleRegUsers.java" servlet which acts as a controller for your view "Registration.jsp". So create this HandleRegUsers servlet in "Reg" package as depicted below.

package Reg;

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

import DBCore.HandleDB;

/**
* Servlet implementation class HandleRegUsers
*/
public class HandleRegUsers extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HandleRegUsers() {
super();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
String fname = request.getParameter("fnme");
String lname = request.getParameter("lnme");
String paswd = request.getParameter("paswd");
String country = request.getParameter("country");
String email = request.getParameter("email");
String day = request.getParameter("Date");
String month = request.getParameter("Month");
String year = request.getParameter("Year");
String dob = month+"/"+day+"/"+year;
try {
HandleDB.regUser(fname, lname, dob, paswd, email, country);
request.getSession().setAttribute("name", fname+" "+ lname);
response.sendRedirect("RegSuccess.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

}

You can see that I have created "processRequest()" method which is invoked inside the function called "doGet()". You have to either define exceptions or add try catch appropriately without prompting error in your code.

Now we have already created JSP (View) and Servlet (Controller), we only have to develop now our model class which is a collection of a java classes that form a software applications intended to store , and optionally seperate data.

First we create Java DBC or JDBC connection class where you define and make a connection with jdbc. For that I create a Connector package and inside that I create a java file name as DbCon.java as depicted below.

package Connector;

import java.sql.*;

public class DbCon {
private static Connection c;
public static Connection createCon() throws Exception{
if(c != null){
return c;
}else{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testme";
c = DriverManager.getConnection(url,"root","");
return c;
}
}
}

Now I create data base handling class which is model class in our solution. Inside DBCore package I create HandleDB.java file to handle database queries coming from servlet (Controller) in our case HandleRegUsers .java

This is model class;

package DBCore;

import java.sql.Connection;
import java.sql.ResultSet;

import Connector.DbCon;

public class HandleDB {
private static Connection c;
public static ResultSet fetch(String sql) throws Exception{
c = DbCon.createCon();
return c.createStatement().executeQuery(sql);
}

public static void save(String sql) throws Exception{
c = DbCon.createCon();
c.createStatement().executeUpdate(sql);
}
public static void regUser(String fname, String lname, String dob, String paswd, String email, String contry)throws Exception{
save("INSERT INTO user(email,fname,lname,paswd,country,dob) VALUES('"+email+"','"+fname+"','"+lname+"','"+paswd+"','"+contry+"','"+dob+"')");
}
public static ResultSet getCountry()throws Exception{
return fetch("SELECT * FROM country");
}
public static ResultSet getRegUserData(String uname, String paswd) throws Exception{
return fetch("SELECT * FROM user WHERE email = '"+uname+"'AND paswd = '"+paswd+"'");
}
}

There are two type of very important methods which are called by other methods. These two are fetch and save.
fetch() --> this is used for SELECT, DELETE and UPDATE
save() -->this is used for INSERT

You pass query as a string to one of these two methods appropriately and then they execute this query.

Before you test this you have to make a database schema that should be named as 'testme' and username is root and password is not specified. then I have created a table named user.
DROP TABLE IF EXISTS `testme`.`user`;
CREATE TABLE `testme`.`user` (
`email` varchar(45) collate latin1_general_ci NOT NULL default '',
`fname` varchar(45) collate latin1_general_ci NOT NULL,
`lname` varchar(45) collate latin1_general_ci NOT NULL,
`paswd` varchar(45) collate latin1_general_ci NOT NULL,
`country` varchar(45) collate latin1_general_ci NOT NULL,
`dob` date NOT NULL,
PRIMARY KEY (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
There is another table in order to load countries at the beginning in registration form so that users can pick one. There I haven't hard coded them in jsp, what I have done is I loaded them from data base.

DROP TABLE IF EXISTS `testme`.`country`;
CREATE TABLE `testme`.`country` (
`name` varchar(45) NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Then I must insert countries to this country table in order to display them in Registration.jsp.

After those steps, if successful registration process takes place, you will be redirected to RegSuccess.jsp which is mentioned in HandleRegUsers servlet which I coded above as a controller servlet. So you must create that jsp as well before you run this.
Here is the RegSuccess.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Regisration Succeeded
<% String fullname = (String)session.getAttribute("name") + " ";

%>
<%=fullname %> Registered Successfully

I got registered user's full name here from session and displayed it to him saying "Mr XYZ Registered Successfully". You can do it in different way like after saving them in data base you can retrieve full name from db and then show it which is much appropriate then this way since in this way data might not be stored in db even though you are displayed that you have successfully registered. It can happen since I have added full name into session by getting data from request in HttpRequest, but if you do the same after your data saving part in db completed, then you can grantee they are stored in db, never mind guess you did not get it :)

Now that registered user is going to login.
This is a simple login jsp

<% String chkuser = (String) session.getAttribute("ill");
int i =0;
String data ="";
if(!chkuser.equals("")){
i =1;
}
%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"'/
pageEncoding="ISO-8859-1"%>
Login
<% if(i >= 1){
data = "Provide Username and Password";
}%>
<%= data %>


user Name
Password
Cancel
Register

Forget about very first few lines of this jsp since they are used to display if you have entered wrong user name password combination or you are trying to log in to system illegally (suppose some one logged in same machine and made some transactions and then that person logged out from the system. Now the screen is logging interface. You are now going to access the same machine so you click back button in your browser, Unless I handled it specifically, then you will be redirected to previous persons private logged screen since just after he clicked log out button he was redirected to the screen where you saw when you sit in that machine) So you do not need to pay attention for those lines now.

After you clicked on log button, you will be sent to LogingUser.java servlet file which is again controller and your log in jsp is the view. I have created this servlet inside Login package as below.

package Login;

import java.io.IOException;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Connector.DbCon;
import DBCore.HandleDB;

/**
* Servlet implementation class LogingUser
*/
public class LogingUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogingUser() {
super();
// TODO Auto-generated constructor stub
}

protected void procesRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String uname = request.getParameter("unme");
String paswd = request.getParameter("paswd");
String invalidCombination = "Invalid Combination of Username or Pasword or both";
String illigalAccessing = "Need to be loged in first";
try {
ResultSet rs = HandleDB.getRegUserData(uname,paswd);
if(rs.next()){
while(rs.next()){
request.getSession().setAttribute("ill", illigalAccessing);
String fullNme = rs.getString("fname")+" "+ rs.getString("lname");
request.getSession().setAttribute("name", fullNme);
response.sendRedirect("AdminPage.jsp");
}
}else{
request.getSession().setAttribute("invalid", invalidCombination);
response.sendRedirect("Login.jsp");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
procesRequest(request, response);// TODO Auto-generated method stub
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

I have created procesRequest() method and it is invoked inside doGet() method which is same process I followed in previous registration process.

ResultSet rs = HandleDB.getRegUserData(uname,paswd);

This line shows that I have called getRegUserData() method in HandleDB model class by passing username and password as a parameters.

In HandleDB.java

public static ResultSet getRegUserData(String uname, String paswd) throws Exception{
return fetch("SELECT * FROM user WHERE email = '"+uname+"'AND paswd = '"+paswd+"'");
This return all details about that provided username and password fields which mean if a particular user provides correct username and password he will be directed to his profile.

So you will be redirected to AdminPage.jsp which is mentioned in this LogingUser servlet class.

Now I have created that AdminPage.jsp


<% String illigal= (String) session.getAttribute("ill");
if(illigal.equals("")){
session.setAttribute("ill", illigal);
response.sendRedirect("Login.jsp");
}
%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Welcome
<% String fname = (String) session.getAttribute("name"); %>
LogoutWelcome <%= fname %> to Admin Console

Now I have showed you how simple JSP/Servlet can be implemented using MVC, this is really a simple way of letting MVC in action. You can plug session beans and entity beans as i stated above at the very beginning.

Comments

Popular Posts