Monday, July 24, 2017

MVC Framework

In the beginning there was darkness (and simplicity). The only things that existed were static html pages. They would have html and text, and that's it.
Soon after, Servlets were created to allow dynamic pages to be written using the Java language.

public class ABCServlet extends HttpServlet
{
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
   PrintWriter out = response.getWriter();
   out.println("<html><head><title>A Nice Servlet</title></head><body>");
   out.println("The nice body of this servlet displays the date for you: "+(new java.util.Date()));
   out.println("</body></html>");
   out.close();
 }
}

But things became complicated, because creating large dynamic html page content with lots of data required many lines of out.println() statements. So something else came along.

With the creation of JSP pages, you could now write a Scriptlet or Expression, Standard Actions, EL (JSP Expression Language), JSTL and the Servlet Container (eg. Tomcat) would dynamically generate all the servlet code for you automatically (eg. all the out.println() statements).

MVC is a systematic way to use the application where the flow starts from the view layer, where the request is raised and processed in controller layer and sent to model layer to insert data and get back the success or failure message.

Servlet/JSP MVC architecture :-

1. A form(html/jsp) with two variables "email" and "password" which is our view layer.
2. Once the user enters email, and password and clicks on submit then the action is passed in MVCServlet where email and password are passed.
3. This MVCServlet is controller layer(servlet). Here in MVCServlet the request is sent to the bean object which act as model layer(bean).
4. The email and password values are set into the bean and stored for further purpose.
5. From the bean, the value is fetched and shown in the view layer(jsp).


form.jsp(View)
    <%@ 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="MVCServlet" method="POST">
    Email: <input type="text" name="email">
    <br />
    Password: <input type="text" name="password" />
    <input type="submit" value="Submit" />
    </form>
    </body>
    </html>

browser sends http request to web server, container create httpServletRequest and httpServletResponse objects for this http request. Now container see requested url and maps to specific servlet
reuest.getURL() -> server:port/hello
/hello -> mapping HelloServlet (Controller)
Model
View


MVCServlet.java(Controller)
public class MVCServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String email=request.getParameter("email"); 
        String password=request.getParameter("password");
       
        TestBean testobj = new TestBean();
        testobj.setEmail(email);
        testobj.setPassword(password);
        request.setAttribute("testbean",testobj);
        RequestDispatcher rd=request.getRequestDispatcher("mvcsuccess.jsp"); 
        rd.forward(request, response);
    }

}

TestBean.java(Model)
public class TestBean implements Serializable{
   
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    private String email="null";
    private String password="null";
}

mvcsuccess.jsp(View)
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@page import="demotest.TestBean"%>
    <!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>
    <% 
    TestBean testguru=(TestBean)request.getAttribute("testbean"); 
    out.print("Welcome, "+testguru.getEmail()); 
    %>
    </body>
    </html>



Spring MVC Framework :-
Spring MVC is based on servlet and jsp technology implement model-view-controller design pattern.


Spring MVC framework is designed around a central Servlet called DispatcherServlet that handles all the HTTP requests and responses. It is completely integrated with the Spring IoC container so it allows you to use every feature that Spring has.

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −

1. After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.

2. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.

3. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.

4. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.

<web-app>
  <display-name>Archetype Created Web Application</display-name>
 
  <servlet>
        <servlet-name>spring</servlet-name>
            <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            </servlet-class>

    <init-param>
        <param-name>contextConfigLocation</param-name> //setter method
        <param-value>/WEB-INF/webApplicationContext.xml</param-value> //custom name
    </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
   
</web-app>


By default,
DispatcherServlet loads its configuration file using <servlet-name>-servlet.xml.
E.g. with above web.xml file, DispatcherServlet will try to find spring-servlet.xml file in classpath.

DispatcherServlet (actually a servlet) is the front controller in Spring MVC that intercepts every request and then dispatches/forwards requests to an appropriate controller. 

Listener class - Listens on an event

ContextLoaderListener -
    1. Listens during server start up/shutdown
    2. Reads the spring configuration file (with value given against “contextConfigLocation” in web.xml), parse it and loads the beans defined in that config file(destroys the bean during shutdown)
    3. Configuration files can be provided in web.xml
    
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>


Basically you can isolate your root application context and web application context using ContextLoaderListner.

The config file mapped with context param will behave as root application context configuration. And config file mapped with dispatcher servlet will behave like web application context.

We should define our common services, entities, aspects etc in root application context. And controllers, interceptors etc are in relevant web application context.

OR When you want to put your Servlet file in your custom location or with custom name, rather than the default naming convention [servletname]-servlet.xml and path under Web-INF/ ,then you can use ContextLoaderListener.

No comments:

Post a Comment

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...