J2EE Model View Controller Pattern TutorialData Model For this example we use a very simple bean as a model. The rules for writing a JavaBean must provide a constructor that takes no arguments ; it must not have any public variables; and any access to bean state should take place through getXXX() and setXXX() accesor methods. Business methods are other methods that operate on the model data. The interface of the Data Model bean. public interface MailingBean{ //first name public String getFirst( ); public void setFirst(String first); //middel name public String getMiddel( ); public void setMiddel(String middel); //last name public String getLast( ); public void setLast(String last); //address public String getAddress( ); public void setAddress(String address); //apartment public String getApartment( ); public void setApartment(String apartment); //city public String getCity( ); public void setCity(String city); //state public String getState( ) ; public void setState(String state); //zip public String getZip( ) ; public void setZip(String zip); //country public String getCountry( ); public void setCountry(String country); //telephone1 public String getTelephone1( ); public void setTelephone1(String telephone1); //telephone2 public String getTelephone2( ); public void setTelephone2(String telephone2); //cellular public String getCellular( ); public void setCellular(String cellular); //email1 public String getEmail1( ); public void setEmail1(String email1); //email2 public String getEmail2( ); public void setEmail2(String email2); //business method public boolean doSubscribe( ); //subscription result public String getErrorString( ); } Controller Moving on to the Controller after Data Model set. To get a new instance of a MailingBean: MailingBeanFactory.newInstance(); In J2EE, The controller should be implemented as a servlet. There are many possible designs. The doGet() method provides us all the information we need to perform these tasks. We can retrieve information from the request including the first, middel, and last, parameters submitted via the form. The first step-reading the request---the server API provides us with an HttpServletRequest object. The servlet container creates this object based on the data from the web server. When the servlets doGet() method is called it is passed an instance of HttpServletRequest. One of the main functions of this object is to make the request parameters available to the servlet. To retrieve a parameter, we use tyhe getParameter() method, passing it in the name of the field as defined inthe HTML form. In order to read the email address parameter we use the code: String email mb = request.getParameter("email"); The second step requires working with the model. the exact mothods of interacting weith the model vary based on the details of the model and what exactly the servlet is trying to do. When working with a JavaBean based model, the servlet typically creates a new bean using a factory, or locates an existing one via a look-up service like JNDI MailingBean mb = MailingBeanfactory.newInstance(): Once the bean exists, it can be manipulated. here it means setting the values of various fields and then calling business methods to interact with the actual mailing list software. Foe example mb.setEmail(email); The third step is to store model information for use by the view.In this example we simply store a reference to our MailingBean in the request scope, so it can be manipulated by the view. To do this we use another method of the HttpServletRequest object, setAttribute(); request.setAttribute("mailingbean, mb"); Along with the bean itself we also use a string key. This is important, because it will be used by the bean to identify the bean in question.Once control passes to the view. the controller has done its job. We tranfer control using the RequestDispatcher object, which is used to forward requests within the server. We simply provide a URL to the request dispatcher, and use the forward() method to transfer control. RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextPage); dispatcher.forward(request, response); The steps described above are illusrtated in the sample code below. Script 1.0 Registration /* // // $Models.iNetmodels.Com-Id:Administrator 12:00 PM 07/20/2006 $ // Copyright (C) 2006 The iNetModel Development Team // Model-View-Controller Pattern Models.iNetModels.Com // // Script 1.0 ListController Servlet // */ Import javax.servlet.*; Import javax.servlet.http.*; Import javax.io.IOException; public class ListController extends HttpServlet { public static final String EMPID_PARAM = "empid"; public static final String FIRST_PARAM = "first"; public static final String MIDDEL _PARAM = "middel"; public static final String LAST_PARAM = "last"; public static final String ADDRESS_PARAM = "address"; public static final String APARTMENT_PARAM = "apartment"; public static final String CITY_PARAM = "city"; public static final String STATE_PARAM = "state"; public static final String ZIP_PARAM = "zip"; public static final String COUNTRY_PARAM = "country"; public static final String TELEPHONE1_PARAM = "telephone1"; public static final String TELEPHONE2_PARAM = "telephone2"; public static final String CELLULAR_PARAM = "cellular"; public static final String EMAIL1_PARAM = "email1"; public static final String EMAIL2_PARAM = "email2"; public static final String MAILINGBEAN_ATTR= "mailingbean"; public void init(ServletConfig config) throws ServletException { super.init(config); } public void destroy( ) { } // handle get requests protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //read the parameters from the request String empid = request.getParameter(EMPID_PARAM); String first = request.getParameter(FIRST_PARAM); String middel = request.getParameter(MIDDEL_PARAM); String last = request.getParameter(LAST_PARAM); String address = request.getParameter(ADDRESS_PARAM); String apartment = request.getParameter(APARTMENT_PARAM); String city = request.getParameter(CITY_PARAM); String state = request.getParameter(STATE_PARAM); String zip = request.getParameter(ZIP_PARAM); String country = request.getParameter(COUNTRY_PARAM); String telephone1 = request.getParameter(TELEPHONE1_PARAM); String telephone2 = request.getParameter(TELEPHONE2_PARAM); String cellular = request.getParameter(CELLULAR_PARAM); String email1 = request.getParameter(EMAIL1_PARAM); String email2 = request.getParameter(EMAIL2_PARAM); //get the mailing list bean for this list MailingBean mb = MailingBeanFactory.newInstance( ); //get the parameters into the bean mb.setEmpid(empid); mb.setFirst(first); mb.setMiddle(middle); mb.setLast(Last); mb.setAddress(address); mb.setApartment(apartment); mb.setCity(city); mb.setState(state); mb.setZip(zip); mb.setCountry(country); mb.setTelephone1(telephone1); mb.setTelephone2(telephone2); mb.setCellular(cellular); mb.setEmail1(email1); mb.setEmail2(email2); //store a copy of the bean in the request context request.setAttribute(MAILINGBEAN_ATT,mb); //perform the business method boolean result = mb.doSubscribe( ); //choose a page based on the result String nextpage ="/success.jsp"; if (!result) nextPage ="failture.jsp"; //transfer control to the selected view RequestDispatcher dispatcher = getServletContext( ).getRequestDispatcher(nextPage); dispatcher.forward(request, response); } } View Once the controller has finished actively processing the request things turn over to the view. For web-based presentation tiers the view is anything that writes to the Http reponse. It can be a servlet, a JSP, or even a regular HTML file. Using a servlet as a view tends to create a maintenance nightmare, since each change requires a recompilation and redeployment. A JSP page consists of normal HTML with various JSP directives intersparsed. The view must be able to read its data from the model. Since the controller has already stored the model as a Javabean in requst scope, retrieving the model can be done with a single JSP directive: < jsp:useBean id="mailingbean" scope="request" class="models.model.MailingBean" / > This simple directive looks in the current request for an instance of class MailingBean with key "mailingbean". Since this key matches the bean that was added by the controller, the bean should be found.It is now available with the ID "mailingbean" to the jsp:getProperty and jsp:setProperty directives. In order to dynamically binclude the users email address we can use the directive: < jsp:getProperty name="mailingbean" property="email"/ > Note the spelling and the capitalization of the property element must match the spelling and capitalization of the bean method exactly, with the first letter lowercase. The JSP page will simply generate a text message based on whether the MailingBean's business methods succeeded or failed. failure.jsp < %page contentType="text/html"% > < jsp:usebean id="mailingbean" scope="request" class="MailingBean"/ > < html> < head> < title>Subcription Results< /title> < /head> Dear< jsp:getProperty name="mailingbean" property="first"/ > Were sorry the address< jsp:getProperty name="mailingbean" property="email"/ > could not be added top the list. The problem was< jsp:getProperty name="mailingbean" property="errorstring"/ > Sincerely, Administrator WWW.iNetModel.Com |