View RSS Feed

My Java Tips

MVC Controller

Rate this Entry
by , 11-19-2011 at 05:07 PM (985 Views)
In this post, I will briefly talk about MVC controller.


Controller manages users interaction with the system. The component Controller is perhaps the most important component in the MVC architecture. It invokes the component Model and the component View and also couples these two that is View with the Model. If the application requires, it may invoke multiple Views and may couple them with the same Model. It listens to the user actions and according to business rules manipulates the Model.

The Controller can runtime create an appropriate View depending on Model as in MVC architecture application behavior (Controller) is separate from data presentation (View). Similarly MVC architecture allows the users requests to be mapped from the controller to specific application level functions in the model as the application behavior (View) is separate from data representation (Model).

In our example of online website for shopping books, the processing for all actions carried out within either Eshop.jsp or Cart.jsp is handled by the controller servlet, ShoppingServlet.java. That is the servlet ShoppingServlet.java acts as the component Controller. The controller servlet handles the request processing and the creation of any beans or objects used by the JSP. It also decides that to which JSP pages requests are to be forwarded.



Every time the user adds a book using EShop.jsp, the request is posted to the controller servlet ShoppingServlet.java, for example the user deleting books from the shopping cart, or proceeding to the checkout counter etc. Then servlet takes an appropriate action, and processes the request parameters for the item to be added. It then instantiates a new BOOK bean representing the selection, and goes about updating the shopping cart object before placing it back within the session.

ShoppingServlet.java
Java Code:
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import shopping.BOOK;
public class ShoppingServlet extends HttpServlet {
  public void init(ServletConfig conf) throws ServletException  {
    super.init(conf);
  }
  public void doPost (HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    HttpSession session = req.getSession(false);
    if (session == null) {
      res.sendRedirect("http://localhost:8080/error.html");
    }
    Vector buylist=
      (Vector)session.getValue("shopping.shoppingcart");
    String action = req.getParameter("action");
    if (!action.equals("CHECKOUT")) {
      if (action.equals("DELETE")) {
        String del = req.getParameter("delindex");
        int d = (new Integer(del)).intValue();
        buylist.removeElementAt(d);
      } else if (action.equals("ADD")) {
        //any previous buys of same book?
        boolean match=false;
        BOOK aBOOK = getBOOK(req);
        if (buylist==null) {
          //add first book to the cart
          buylist = new Vector(); //first order
          buylist.addElement(aBOOK);
        } else { // not first buy
          for (int i=0; i< buylist.size(); i++) {
            BOOK book = (BOOK) buylist.elementAt(i);
            if (book.getBook().equals(aBOOK.getBook())) {
              book.setQuantity(book.getQuantity()+aBOOK.getQuantity());
              buylist.setElementAt(book,i);
              match = true;
            } //end of if name matches
          } // end of for
          if (!match)
            buylist.addElement(aBOOK);
        }
      }
      session.putValue("shopping.shoppingcart", buylist);
      String url="/jsp/shopping/EShop.jsp";
      ServletContext sc = getServletContext();
      RequestDispatcher rd = sc.getRequestDispatcher(url);
      rd.forward(req, res);
    } else if (action.equals("CHECKOUT"))  {
      float total =0;
      for (int i=0; i< buylist.size();i++) {
        BOOK anOrder = (BOOK) buylist.elementAt(i);
        float price= anOrder.getPrice();
        int qty = anOrder.getQuantity();
        total += (price * qty);
      }
      total += 0.005;
      String amount = new Float(total).toString();
      int n = amount.indexOf('.');
      amount = amount.substring(0,n+3);
      req.setAttribute("amount",amount);
      String url="/jsp/shopping/Checkout.jsp";
      ServletContext sc = getServletContext();
      RequestDispatcher rd = sc.getRequestDispatcher(url);
      rd.forward(req,res);
    }
  }
  private BOOK getBOOK(HttpServletRequest req) {
    String myBook = req.getParameter("BOOK");
    String qty = req.getParameter("qty");
    StringTokenizer t = new StringTokenizer(myBook,"|");
    String author = t.nextToken();
    String price = t.nextToken();
    price = price.replace('$',' ').trim();
    BOOK book = new BOOK();
    book.setBook(book);
    book.setAuthor(author);
    book.setPrice((new Float(price)).floatValue());
    book.setQuantity((new Integer(qty)).intValue());
    return book;
  }
}

Submit "MVC Controller" to Facebook Submit "MVC Controller" to Digg Submit "MVC Controller" to del.icio.us Submit "MVC Controller" to StumbleUpon Submit "MVC Controller" to Google

Comments