Monday, October 13, 2014

Step by Step explanation of MVC

What is MVC?
Model View Controller is a Architectural  design pattern widely used in most of the modern day enterprise applications.

  • Model:- This is the pojo which will be  carrying the data to the view after processing the request of the ui.
  • View:- These are the ui components which can be written in different languages like html , jsp and so on.
  • Controller:- This is where the actual request goes to when the ui calls a particular http method.



Now that your understanding towards MVC theoretically is complete lets see a small example of the mvc implementation.

Example below is the sample web based application which gives a login screen and once username and password is entered it goes to the db table and verifies if the user is valid or not.

We have used simple jsp and servlet plus java jdbc implementation.

Step1: Download and install Mysql Community server (db server) , and the MySql workbench (ui) for the server.  Create the schema with any name but for the example purpose i have created a java_test schema and user table.


Step2: Create a web project as shown below in the screen shot.

Donot forget to add the servlet api for the servlet container and mysql connector  which is required for the connection to the database.

Step3:- create a login.jsp page in the webcontent folder as shown in above step.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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">
</head>
<body>
<form action="login" method="post">
<center>
<table border="1">

<%
if(request.getAttribute("isError") != null){
%>
<tr>
<td align="center" colspan="2"><font color="red"><%= request.getAttribute("isError") %> </font></font></td>
</tr>

<% } %>

<tr>
<td align="center" colspan="2" style="background: gray;">
Welcome Please Enter Username and password to login</td>
</tr>
<tr>
<td align="left">USERNAME</td>
<td><input type="text" id="username" name="username">
</td>
</tr>
<tr>
<td align="left">PASSWORD</td>
<td><input type="password" id="password" name="password">
</td>
<%
if(request.getAttribute("isPasswordError") != null){
%>
<tr>
<td align="center" colspan="2"><font color="red"><%= request.getAttribute("isPasswordError") %> </font></font></td>
</tr>

<% } %>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit"
value="login" align="center" style="background-color: green;"></td>
</tr>
</table>
</center>
</form>
</body>
</html>
.

Step4:  Now start creating your DBUtil class which fetches you the database connection and then create a DAO(data access object for the table)  user.

package com.test.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtil {

public static Connection getConnection(){
Connection conn=null;
try{
Class.forName("com.mysql.jdbc.Driver");

   //STEP 3: Open a connection
   System.out.println("Connecting to database...");
    conn= DriverManager.getConnection("jdbc:mysql://localhost:3306","root","admin");
   
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
}

DAO's


package com.test.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.test.util.DBUtil;

public class UserDAO {

public boolean isvaliduser(String username , String password){
Connection conn = DBUtil.getConnection();
String sql = "Select * from java_test.user where username=? and password=?";
boolean resp = false;
try {
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
resp = st.execute();
     st.close();
     conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
}


Step 5: create the Servlets which process the request from the browser .


package com.test.servlets;

import java.io.IOException;

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

import com.test.dao.UserDAO;

public class LoginServlet  extends HttpServlet{

/**
*/
private static final long serialVersionUID = -1744569280855263417L;

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String pwd = request.getParameter("password");
UserDAO dao = new UserDAO();
if(dao.isvaliduser(username, pwd)){
RequestDispatcher dispatcher = request.getRequestDispatcher("login2");
request.setAttribute("Success", "loginSuccess. Welcome Mr.Sreeharsha Panguluri");
dispatcher.forward(request, response);
// response.sendRedirect("employee.jsp");
}else{
RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
request.setAttribute("isError", "Your Login information is incorrect Please Enter Username and password to login ");
dispatcher.forward(request, response);
}
}
}


Servlet2

package com.test.servlets;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class LoginServletWithSendReDirect
 */
public class LoginServletWithSendReDirect extends HttpServlet {
private static final long serialVersionUID = 1L;
       
   @Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

  PrintWriter writer = response.getWriter();
  
  writer.print("Hello welcome to my application");
  
  if(request.getAttribute("Success") != null){
  writer.print("<h1>"+(String)request.getAttribute("Success")+"</h1>");
  }
   }

}
.

In the above servlet if you observe we can use response.sendRedirect("employee.jsp") , dispatcher.forward(request, response);  which forwards the request to employee.jsp and you can bind an object to this jsp . THERE YOU GO now compare this with the architectural diagram of MVC.  Any MVC implementation for example SPRING MVC follows the same structure and if you dig deep in to it underneath the spring mvc framework you will find Redirect and Forward.  

Please google the differences between response.sendRedirect vs dispatcher.forward.  VERY IMPORTANT IN UNDERSTANDING OF MVC .


Step 6: Define the Web.xml file which is the Brain of the webapplication.  When the browser sends a request to the application the first place the webcontainer looks in to is the web.xml for all the servlet mappings.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>RequestDispatcherWebApp</display-name>
  
   <welcome-file-list>
    <welcome-file>Login.jsp</welcome-file>
  </welcome-file-list>
  
  
  <servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.test.servlets.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  
  
   <servlet>
    <servlet-name>login2</servlet-name>
    <servlet-class>com.test.servlets.LoginServletWithSendReDirect</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>login2</servlet-name>
    <url-pattern>/login2</url-pattern>
  </servlet-mapping>


</web-app>


This is where we define our servlets and their mapping.  Please go through the components in the web.xml .
servlet: defines the servlet and its class

servlet-mapping:  defines the mapping of the servlet.

url-pattern  defines the path to the servlet . e.g., /login

Welcome-file-list  denotes the welcome file to be loaded when the webapplication is hit from the browser after deploying to the appserver.

Note:- Go through the different components in the web.xml to understand what all can be defined here.

Once all the above mentioned steps are done then you app is ready to get deployed.

If you are using eclipse

  • right click on the webapp and run as   select what ever app server you have.  
  • In this example am using the jetty server.
If you donot see any errors in the console your successful deployment will be as shown below.







Note:-  One thing we need to make a note is the CONTEXT for the webapplication .  Context is the unique name by which Web container in the appserver identifies your web application .

For example if you have 5 webapplications deployed in your app server instance then when the browser makes a request to number 3 webapplication the only way how the container in the app server will find out is based on the CONTEXT.

Now that you understand the context lets ping our webapplication running at port 8080.

http://localhost:8080/RequestDispatcherWebApp



You will see the login screen and that is it . Now you can enter the username password in entered in your database and debug through the whole flow and compare it with the architectural diagram of MVC .

HAPPY LEARNING!!!!!!

Please leave a comment if this is helpful

No comments:

Post a Comment