J2EE的MVC模式

来源:互联网 发布:网店美工 编辑:程序博客网 时间:2024/05/17 07:36
在J2EE设计模式一书中的第三章看到了MVC模式,并给出了Email注册的例子来详细阐释但没有详细代码,就动手写了一下以期更好地理解MVC模式,顺便复习下零星学的jsp.
文献:J2EE设计模式 William Crawford JonathanKaplan。CH3表达层
   http://en.wikipedia.org/wiki/JavaBeans
工程位置:Lomboz /MVCBean_v0.1 
在mysql中新建了数据库maildata,该数据库中建了表mail.
maildata.sql:
create database maildata;use maildata;create table mail(        id int primary key auto_increment,first varchar(255),last varchar(255),email text);insert into article values(null,'Biang','Hoo','cbw3029798@126.com');


描述:模拟一个邮箱的注册过程
客户端:
client的登录界面subscribe.html:
<html><head><title>Subscribe</title></head><body><hr><br><form align=center action="/ListController" method="get">First Name:<input type="text"name="first"><br>Last Name:<input type="text"name="last"><br>Email Address:<input type="text"name="email"><br><input type="submit" name="提交"></input></form></body></html>


服务器端的用户接口MVC
MVC将用户接口问题分割成三个截然不同的部分:模型,视图和控制器。模型存储应用的状态,视图解释模型中的数据并将它展示给用户,最后控制器处理用户的输入,然后或者更新模型或者显示新的视图
Controller:控制器的工作包括:1.读取请求,
2。协调到模型的访问,
3存储用于视图的模型信息,
4将控制转给视图。
一般为servlet,控制业务逻辑:在本例中为ListController并体现了上述四点功能
import javax.servlet.ServletException;import javax.servlet.http.*;import javax.servlet.*;import bean.MailingBeanFactory;import java.io.IOException;/** * @author Bangwen Chen * * 2013-8-5 */public class ListController extends HttpServlet {public static final String FIRST_PARM = "first";public static final String LAST_PARM = "last";public static final String EMAIL_PARM = "email";public static final String MAILINGBEAN_ATTR = "mailingbean";protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String first = req.getParameter(FIRST_PARM);//读取请求String last = req.getParameter(LAST_PARM);String email = req.getParameter(EMAIL_PARM);MailingBeanFactory mb = MailingBeanFactory.newInstance();//协调到模型的访问mb.setFirst(first);mb.setLast(last);mb.setEmail(email);req.setAttribute(MAILINGBEAN_ATTR,mb);//存储用于视图的模型信息boolean result = mb.doSubscribe();String nextPage = "/success.jsp";if(!result){nextPage="/failure.jsp";}RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextPage);//将控制转给视图dispatcher.forward(req,resp);}}


Model:模型,模型的设计是以数据为中心的,在J2EE的世界里,模型通常是JavaBean或EJB,
    JavaBean是java中可以重复使用的组建,实际上,他们就是一些把许多对象放到一个对象(就是Bean)的类。他们是序列化的,即可以直接被IO操作,必须有不带参数的构造函数,并且可以通过getter和setter方法来访问属性。JavaBean不要写成裸体类,而是应该包含在包中。它的优点有:1,write once,run anywhere 2,暴露给其他应用的属性,事件和方法是可控的。。。等等
 在本例中为MailingBeanFactory,负责与数据库的连接及操作,为了方便对数据库进行操作还使用了以前封装过DB类用于数据库的连接,代码如下:
package bean;import java.sql.*;/** * @author Bangwen Chen * * 2013-7-15 */public class DB {public static Connection getConn(){Connection conn =null;try{Class.forName("com.mysql.jdbc.Driver");//MySQLconn=DriverManager.getConnection("jdbc:mysql://localhost/maildata?user=root&password=admin411");//Class.forName("oracle.jdbc.driver.OracleDriver");//ORACLE//conn=DriverManager.getConnection("jdbc:oracle:thin:@GG:1521:orcl","scott","admin411");}catch(ClassNotFoundException e){e.printStackTrace();}catch(SQLException e){e.printStackTrace();}return conn;}public static Statement getStmt(Connection conn){Statement stmt=null;try{if(conn!=null){stmt = conn.createStatement();}}catch(SQLException e){e.printStackTrace();}return stmt;}public static PreparedStatement getPreStmt(Connection conn,String sql){PreparedStatement preStmt=null;try{if(conn!=null){preStmt = conn.prepareStatement(sql);}}catch(SQLException e){e.printStackTrace();}return preStmt;}public static ResultSet getRS(Statement stmt,String sql){ResultSet rs =null;try{if(stmt != null){rs=stmt.executeQuery(sql);}}catch(SQLException e){e.printStackTrace();}return rs;}public static void closeConn(Connection conn) {try {if(conn != null) {conn.close();conn = null;}} catch (SQLException e) {e.printStackTrace();}}public static void closeStmt(Statement stmt) {try {if(stmt != null) {stmt.close();stmt = null;}} catch (SQLException e) {e.printStackTrace();}}public static void closePreStmt(PreparedStatement preStmt) {try {if(preStmt != null) {preStmt.close();preStmt = null;}} catch (SQLException e) {e.printStackTrace();}}public static void closeRs(ResultSet rs) {try {if(rs != null) {rs.close();rs = null;}} catch (SQLException e) {e.printStackTrace();}}}
接口MailingBean
package bean;public interface MailingBean {/** * @author Bangwen Chen * * 2013-8-5 *///first namepublic String getFirst();public void setFirst(String first);//last namepublic String getLast();public void setLast(String last);//emailpublic String getEmail();public void setEmail(String email);//public boolean doSubscribe();public String getErrorString();}

实现类MailingBeanFactory
package bean;import java.sql.*;
/** * @author Bangwen Chen * * 2013-8-5 */
public class MailingBeanFactory implements MailingBean{/** * @author Bangwen Chen * * 2013-8-5 */String first ="first";String last = "last";String email ="biang@126.com";Connection conn = null;PreparedStatement preStmt = null;public MailingBeanFactory(){ conn=DB.getConn();//Statement stmt=DB.getStmt(conn);String sql="insert into mail values(?,?,?,null)"; preStmt =DB.getPreStmt(conn, sql); } public static MailingBeanFactory newInstance(){ return new MailingBeanFactory(); } public String getFirst(){return first;}public void setFirst(String first){this.first = first;try{preStmt.setString(1, first);}catch(SQLException e){e.printStackTrace();}}//last namepublic String getLast(){return last;}public void setLast(String last){this.last=last;try{preStmt.setString(2, last);}catch(SQLException e){e.printStackTrace();}}//emailpublic String getEmail(){return email;}public void setEmail(String email){this.email = email;try{preStmt.setString(3, email);}catch(SQLException e){e.printStackTrace();}}//public boolean doSubscribe(){boolean subscribe = true;try{preStmt.addBatch();preStmt.executeBatch();}catch(SQLException e){e.printStackTrace();subscribe = false;}finally{DB.closePreStmt(preStmt);DB.closeConn(conn);}return subscribe=true;}public String getErrorString(){return " ";}}
View:jsp,更新用户视图本例中实现了success.jsp failure.jsp。
success.jsp
<%@ page import="bean.*"%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><jsp:useBean id="mailingbean" scope="request" class="bean.MailingBeanFactory" ></jsp:useBean><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Subscription Results</title></head><body><br><br>Dear <jsp:getProperty name="mailingbean" property="first"/>,<br><br>Congratulations!! the address<jsp:getProperty name="mailingbean" property="email"/>has subscribed successfully!!</body></html>

failure.jsp
<%@ page import=bean.*%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>    <jsp:useBean id="mailingbean" scope="request" class="bean.MailingBeanFactory" /><!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=UTF-8"><title>Subscription Results</title></head><body><br><br>Dear <jsp:getProperty name="mailingbean" property="first"/>,<br><br>I am sorry to tell you that the address<jsp:getProperty name="mailingbean" property="email"/> could not be added to the list !!
the problem was: 
I'm too lazy to write the code,so I just omit it......</body></html>

tomcat中的部署:
webapps下新建了mail目录【WEB-INF(lib,classes),web,xml】

整个流程 :客户端访问subscribe.html;并填写注册信息然后发送给控制器(ListController),控制器读取用户请求,更新模型(MialingBeanFactory)存储状态,并取得用于视图的模型信息,然后根据模型的更新结果将控制转给视图,视图将对应的页面(注册成功/失败)返回给用户。。


原创粉丝点击