MVC模式示例

来源:互联网 发布:淘宝访问深度怎么算 编辑:程序博客网 时间:2024/06/06 03:42

MVC架构模式:

View(视图层)、Control(控制层)、Model(模型层)


Model(模型层)

模型包括两部分,一个是对应数据库的映射,另一个是对数据库对应映射的方法(比如数据库操作的增、删、改、查,简称C(CREAT)R(RETRIEVE)U(UPDATE)D(DELETE))其中R,查询,包括高级查询,包括报表、分页等;

Control(控制层)

控制数据流通过程

View(视图层)

将拼装起来的数据进行展示


1.控制层起到桥梁的作用,接收视图层传过来的参数,调用模型层,模型层将结果通知给控制层,控制层来更新视图层。

2.View(前端)可能是图片,也可能是数据列表,用户修改了数据之后,视图层将用户的这个行为传递到控制层(用于协调控制),控制层更新模型层(数据处理),模型层处理之后通知控制层,控制层再更新视图层(这时用户看到的就是修改之后的最新视图层)

3.把视图层的展示、业务逻辑、数据存储的过程分开,通过控制层协调控制。每一部分由相应的人员负责,更有利于协调工作 。

                                             

        设计时由 数据库-模型层-控制层-视图层的顺序进行设计      

在MyEclipse利用Java代码生成的UML类图


GoddessAction.java:

执行GoddessDao里的操作

package com.imooc.action;import java.sql.SQLException;import java.util.List;import java.util.Map;import com.imooc.dao.GoddessDao;import com.imooc.model.Goddess;public class GoddessAction {public void add(Goddess goddess) throws Exception{GoddessDao dao=new GoddessDao();goddess.setSex(1);goddess.setCreate_user("ADMIN");goddess.setUpdate_user("ADMIN");goddess.setIsdel(0);dao.addGoddess(goddess);}public Goddess get(Integer id) throws SQLException{GoddessDao dao=new GoddessDao();return dao.get(id);}public void edit(Goddess goddess) throws Exception{GoddessDao dao=new GoddessDao();dao.updateGoddess(goddess);}public void del(Integer id) throws SQLException{GoddessDao dao=new GoddessDao();dao.delGoddess(id);}public List<Goddess>  query() throws Exception{GoddessDao dao=new GoddessDao();return dao.query();}public List<Goddess> query(List<Map<String, Object>> params) throws Exception{GoddessDao dao=new GoddessDao();return dao.query(params);}}

GoddessDao.java:

对Goddess进行增删改查操作

package com.imooc.dao;import java.sql.Connection;import java.sql.Date;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.Map;import com.imooc.db.DBUtil;import com.imooc.model.Goddess;public class GoddessDao {public void addGoddess(Goddess g) throws Exception{Connection conn=DBUtil.getConnection();String sql="" +"insert into imooc_goddess" +"(user_name,sex,age,birthday,email,mobile," +"create_user,create_date,update_user,update_date,isdel)" +"values(" +"?,?,?,?,?,?,?,current_date(),?,current_date(),?)";PreparedStatement ptmt=conn.prepareStatement(sql);ptmt.setString(1, g.getUser_name());ptmt.setInt(2, g.getSex());ptmt.setInt(3, g.getAge());ptmt.setDate(4, new Date(g.getBirthday().getTime()));ptmt.setString(5, g.getEmail());ptmt.setString(6, g.getMobile());ptmt.setString(7, g.getCreate_user());ptmt.setString(8, g.getUpdate_user());ptmt.setInt(9, g.getIsdel());ptmt.execute();}public void updateGoddess(Goddess g) throws SQLException{Connection conn=DBUtil.getConnection();String sql="" +" update imooc_goddess " +" set user_name=?,sex=?,age=?,birthday=?,email=?,mobile=?, " +" update_user=?,update_date=current_date(),isdel=? " +" where id=? ";PreparedStatement ptmt=conn.prepareStatement(sql);ptmt.setString(1, g.getUser_name());ptmt.setInt(2, g.getSex());ptmt.setInt(3, g.getAge());ptmt.setDate(4, new Date(g.getBirthday().getTime()));ptmt.setString(5, g.getEmail());ptmt.setString(6, g.getMobile());ptmt.setString(7, g.getUpdate_user());ptmt.setInt(8, g.getIsdel());ptmt.setInt(9, g.getId());ptmt.execute();}public void delGoddess(Integer id) throws SQLException{Connection conn=DBUtil.getConnection();String sql="" +" delete from imooc_goddess " +" where id=? ";PreparedStatement ptmt=conn.prepareStatement(sql);ptmt.setInt(1, id);ptmt.execute();}public List<Goddess> query() throws Exception{List<Goddess> result=new ArrayList<Goddess>();Connection conn=DBUtil.getConnection();StringBuilder sb=new StringBuilder();sb.append("select id,user_name,age from imooc_goddess  ");PreparedStatement ptmt=conn.prepareStatement(sb.toString());ResultSet rs=ptmt.executeQuery();Goddess g=null;while(rs.next()){g=new Goddess();g.setId(rs.getInt("id"));g.setUser_name(rs.getString("user_name"));g.setAge(rs.getInt("age"));result.add(g);}return result;}public List<Goddess> query(String name,String mobile,String email) throws Exception{List<Goddess> result=new ArrayList<Goddess>();Connection conn=DBUtil.getConnection();StringBuilder sb=new StringBuilder();sb.append("select * from imooc_goddess  ");sb.append(" where user_name like ? and mobile like ? and email like ?");PreparedStatement ptmt=conn.prepareStatement(sb.toString());ptmt.setString(1, "%"+name+"%");ptmt.setString(2, "%"+mobile+"%");ptmt.setString(3, "%"+email+"%");System.out.println(sb.toString());ResultSet rs=ptmt.executeQuery();Goddess g=null;while(rs.next()){g=new Goddess();g.setId(rs.getInt("id"));g.setUser_name(rs.getString("user_name"));g.setAge(rs.getInt("age"));g.setSex(rs.getInt("sex"));g.setBirthday(rs.getDate("birthday"));g.setEmail(rs.getString("email"));g.setMobile(rs.getString("mobile"));g.setCreate_date(rs.getDate("create_date"));g.setCreate_user(rs.getString("create_user"));g.setUpdate_date(rs.getDate("update_date"));g.setUpdate_user(rs.getString("update_user"));g.setIsdel(rs.getInt("isdel"));result.add(g);}return result;}public List<Goddess> query(List<Map<String, Object>> params) throws Exception{List<Goddess> result=new ArrayList<Goddess>();Connection conn=DBUtil.getConnection();StringBuilder sb=new StringBuilder();sb.append("select * from imooc_goddess where 1=1 ");if(params!=null&¶ms.size()>0){for (int i = 0; i < params.size(); i++) {Map<String, Object> map=params.get(i);sb.append(" and  "+map.get("name")+" "+map.get("rela")+" "+map.get("value")+" ");}}PreparedStatement ptmt=conn.prepareStatement(sb.toString());System.out.println(sb.toString());ResultSet rs=ptmt.executeQuery();Goddess g=null;while(rs.next()){g=new Goddess();g.setId(rs.getInt("id"));g.setUser_name(rs.getString("user_name"));g.setAge(rs.getInt("age"));g.setSex(rs.getInt("sex"));g.setBirthday(rs.getDate("birthday"));g.setEmail(rs.getString("email"));g.setMobile(rs.getString("mobile"));g.setCreate_date(rs.getDate("create_date"));g.setCreate_user(rs.getString("create_user"));g.setUpdate_date(rs.getDate("update_date"));g.setUpdate_user(rs.getString("update_user"));g.setIsdel(rs.getInt("isdel"));result.add(g);}return result;}public Goddess get(Integer id) throws SQLException{Goddess g=null;Connection conn=DBUtil.getConnection();String sql="" +" select * from imooc_goddess " +" where id=? ";PreparedStatement ptmt=conn.prepareStatement(sql);ptmt.setInt(1, id);ResultSet rs=ptmt.executeQuery();while(rs.next()){g=new Goddess();g.setId(rs.getInt("id"));g.setUser_name(rs.getString("user_name"));g.setAge(rs.getInt("age"));g.setSex(rs.getInt("sex"));g.setBirthday(rs.getDate("birthday"));g.setEmail(rs.getString("email"));g.setMobile(rs.getString("mobile"));g.setCreate_date(rs.getDate("create_date"));g.setCreate_user(rs.getString("create_user"));g.setUpdate_date(rs.getDate("update_date"));g.setUpdate_user(rs.getString("update_user"));g.setIsdel(rs.getInt("isdel"));}return g;}}

DBUtil.java:

内含有对数据库建立连接的getConnection()方法。

package com.imooc.db;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class DBUtil {private static final String URL="jdbc:mysql://127.0.0.1:3306/imooc?useUnicode=true&characterEncoding=utf-8";private static final String USER="root";private static final String PASSWORD="";private static Connection conn=null;static {try {//1.加载驱动程序Class.forName("com.mysql.jdbc.Driver");//2.获得数据库的连接conn=DriverManager.getConnection(URL, USER, PASSWORD);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}public static Connection getConnection(){return conn;}}

Goddess.java:

Goddess类属性及其get、set方法

package com.imooc.model;import java.util.Date;public class Goddess {private Integer id;private String user_name;private Integer sex;private Integer age;private Date birthday;private String email;private String mobile;private String create_user;private String update_user;private Date create_date;private Date update_date;private Integer isdel;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUser_name() {return user_name;}public void setUser_name(String user_name) {this.user_name = user_name;}public Integer getSex() {return sex;}public void setSex(Integer sex) {this.sex = sex;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getMobile() {return mobile;}public void setMobile(String mobile) {this.mobile = mobile;}public String getCreate_user() {return create_user;}public void setCreate_user(String create_user) {this.create_user = create_user;}public String getUpdate_user() {return update_user;}public void setUpdate_user(String update_user) {this.update_user = update_user;}public Date getCreate_date() {return create_date;}public void setCreate_date(Date create_date) {this.create_date = create_date;}public Date getUpdate_date() {return update_date;}public void setUpdate_date(Date update_date) {this.update_date = update_date;}public Integer getIsdel() {return isdel;}public void setIsdel(Integer isdel) {this.isdel = isdel;}@Overridepublic String toString() {return "Goddess [id=" + id + ", user_name=" + user_name + ", sex="+ sex + ", age=" + age + ", birthday=" + birthday + ", email="+ email + ", mobile=" + mobile + ", create_user=" + create_user+ ", update_user=" + update_user + ", create_date="+ create_date + ", update_date=" + update_date + ", isdel="+ isdel + "]";}}

com.imooc.model.view

View.java

package com.imooc.model.view;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Scanner;import com.imooc.action.GoddessAction;import com.imooc.model.Goddess;public class View {private static final String CONTEXT="欢迎来到女神禁区:\n" +"下面是女神禁区的功能列表:\n" +"[MAIN/M]:主菜单\n" +"[QUERY/Q]:查看全部女神的信息\n" +"[GET/G]:查看某位女神的详细信息\n" +"[ADD/A]:添加女神信息\n" +"[UPDATE/U]:更新女神信息\n" +"[DELETE/D]:删除女神信息\n" +"[SEARCH/S]:查询女神信息(根据姓名、手机号来查询)\n" +"[EXIT/E]:退出女神禁区\n" +"[BREAK/B]:退出当前功能,返回主菜单";private static final String OPERATION_MAIN="MAIN";private static final String OPERATION_QUERY="QUERY";private static final String OPERATION_GET="GET";private static final String OPERATION_ADD="ADD";private static final String OPERATION_UPDATE="UPDATE";private static final String OPERATION_DELETE="DELETE";private static final String OPERATION_SEARCH="SEARCH";private static final String OPERATION_EXIT="EXIT";private static final String OPERATION_BREAK="BREAK";public static void main(String[] args) throws Exception {System.out.println(CONTEXT);Scanner s=new Scanner(System.in);GoddessAction action=new GoddessAction();String pervious=null;Integer step=1;Goddess go=null;while(s.hasNext()){String in=s.next();if(OPERATION_EXIT.equals(in.toUpperCase())||OPERATION_EXIT.substring(0, 1).equals(in.toUpperCase())){System.out.println("您已成功退出女神禁区");break;}else if(OPERATION_MAIN.equals(in.toUpperCase())||OPERATION_MAIN.substring(0, 1).equals(in.toUpperCase())){step=1;pervious=null;go=null;System.out.println(CONTEXT);}else if(OPERATION_QUERY.equals(in.toUpperCase())||OPERATION_QUERY.substring(0, 1).equals(in.toUpperCase())){List<Goddess> list=action.query();for (Goddess goddess : list) {System.out.println(goddess.toString());}}else if(OPERATION_GET.equals(in.toUpperCase())||OPERATION_GET.substring(0, 1).equals(in.toUpperCase())||OPERATION_GET.equals(pervious)){pervious=OPERATION_GET;if(1==step){System.out.println("请输入查询的女神ID:");}else if(step>1){Integer id=null;Goddess g;try {id = Integer.valueOf(in);try {g = action.get(id);if(g==null){System.out.println("查询女神信息失败");}else{System.out.println(g.toString());}} catch (Exception e) {System.out.println("查询女神信息失败");}} catch (Exception e) {System.out.println("请输入正确的女神ID:");}}step++;}else if(OPERATION_ADD.equals(in.toUpperCase())||OPERATION_ADD.substring(0, 1).equals(in.toUpperCase())||OPERATION_ADD.equals(pervious)){pervious=OPERATION_ADD;if(1==step){System.out.println("请输入女神的信息[姓名]:");}else if(2==step){go=new Goddess();go.setUser_name(in);System.out.println("请输入女神的信息[年龄]:");}else if(3==step){Integer age=null;try {age = Integer.valueOf(in);go.setAge(age);System.out.println("请输入女神的信息[生日,格式:2014-12-12]:");} catch (Exception e) {step=2;System.out.println("请输入正确女神的信息[年龄]:");}}else if(4==step){SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");Date birthday=null;try {birthday = sf.parse(in);go.setBirthday(birthday);System.out.println("请输入女神的信息[邮箱]:");} catch (Exception e) {step=3;System.out.println("请输入正确女神的信息[生日]:");}}else if(5==step){go.setEmail(in);System.out.println("请输入女神的信息[手机号]:");}else if(6==step){go.setMobile(in);try {action.add(go);} catch (Exception e) {System.out.println("新增女神信息失败");}System.out.println("新增女神信息成功");step=1;pervious=null;}if(OPERATION_ADD.equals(pervious)){step++;}}else if(OPERATION_UPDATE.equals(in.toUpperCase())||OPERATION_UPDATE.substring(0, 1).equals(in.toUpperCase())||OPERATION_UPDATE.equals(pervious)){pervious=OPERATION_UPDATE;if(1==step){System.out.println("请输入要修改的女神ID:");}else if(2==step){Integer id=null;try {id = Integer.valueOf(in);try {go = action.get(id);if(go==null){System.out.println("查询女神信息失败");step=1;}} catch (Exception e) {System.out.println("查询女神信息失败");step=1;}} catch (Exception e) {System.out.println("请输入正确的女神ID:");step=1;}System.out.println("请输入新的女神信息[姓名],如果不修改该值,请输入-1:");}else if(3==step){if(-1!=Integer.valueOf(in)){go.setUser_name(in);}System.out.println("请输入新的女神信息[年龄],如果不修改该值,请输入-1:");}else if(4==step){Integer age=null;try {age = Integer.valueOf(in);if(-1!=age){go.setAge(age);}System.out.println("请输入新的女神信息[生日,格式:2014-12-12],如果不修改该值,请输入-1:");} catch (Exception e) {step=3;System.out.println("请输入正确女神的信息[年龄]:");}}else if(5==step){SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");Date birthday=null;try {if(-1!=Integer.valueOf(in)){birthday = sf.parse(in);go.setBirthday(birthday);}System.out.println("请输入新的女神信息[邮箱],如果不修改该值,请输入-1:");} catch (Exception e) {step=4;System.out.println("请输入正确女神的信息[生日]:");}}else if(6==step){if(-1!=Integer.valueOf(in)){go.setEmail(in);}System.out.println("请输入新的女神信息[手机号],如果不修改该值,请输入-1:");}else if(7==step){if(-1!=Integer.valueOf(in)){go.setMobile(in);}try {action.edit(go);} catch (Exception e) {System.out.println("更新女神信息失败");}System.out.println("更新女神信息成功");step=1;pervious=null;}if(OPERATION_UPDATE.equals(pervious)){step++;}}else if(OPERATION_DELETE.equals(in.toUpperCase())||OPERATION_DELETE.substring(0, 1).equals(in.toUpperCase())||OPERATION_DELETE.equals(pervious)){pervious=OPERATION_DELETE;if(1==step){System.out.println("请输入要删除的女神ID:");}else if(2==step){Integer id=null;try {id = Integer.valueOf(in);try {action.del(id);step=1;System.out.println("删除女神信息成功");} catch (Exception e) {System.out.println("删除女神信息失败");}} catch (Exception e) {System.out.println("请输入正确的女神ID:");step=1;}}if(OPERATION_DELETE.equals(pervious)){step++;}}else if(OPERATION_SEARCH.equals(in.toUpperCase())||OPERATION_SEARCH.substring(0, 1).equals(in.toUpperCase())||OPERATION_SEARCH.equals(pervious)){pervious=OPERATION_SEARCH;if(1==step){System.out.println("请输入要查询的女神信息,支持姓名、手机号查询,如果两个参数都输入则用逗号分隔[user_name=xx,mobile=xx]:");}else if(2==step){if(in!=null&&in!=""){List<Map<String, Object>> params=new ArrayList<Map<String,Object>>();Map<String, Object> param=null;String[] strs=in.split(",");for (int i = 0; i < strs.length; i++) {String[] strs_s=strs[i].split("=");param=new HashMap<String, Object>();param.put("name", strs_s[0]);param.put("rela", "=");param.put("value", "'"+strs_s[1]+"'");params.add(param);}List<Goddess> list=action.query(params);if(list!=null&&list.size()>0){for (Goddess goddess : list) {System.out.println(goddess.toString());}}else{System.out.println("没有查询到女神信息。。。");}step=1;}}if(OPERATION_SEARCH.equals(pervious)){step++;}}}}}

TestAction.java

package com.imooc.test;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import com.imooc.action.GoddessAction;import com.imooc.model.Goddess;public class TestAction {public static void main(String[] args) throws Exception {GoddessAction action=new GoddessAction();/*查询*//**/Goddess g=new Goddess();g.setUser_name("小青");g.setSex(1);g.setAge(25);g.setBirthday(new Date());g.setEmail("xiaoqing@163.com");g.setMobile("15688888888");g.setIsdel(0);g.setId(7);//action.add(g);//action.edit(g);//action.del(7);List<Map<String, Object>> params=new ArrayList<Map<String,Object>>();Map<String, Object> map=new HashMap<String, Object>();map.put("name", "user_name");map.put("rela", "=");map.put("value", "'小美'");params.add(map);List<Goddess> result=action.query(params);for (int i = 0; i < result.size(); i++) {System.out.println(result.get(i).getId()+":"+result.get(i).getUser_name());}}}

com.imooc.view

View.java

package com.imooc.view;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.Scanner;import com.imooc.action.GoddessAction;import com.imooc.model.Goddess;public class View {private static final String CONTEXT="欢迎来到女神禁区:\n" +"下面是女神禁区的功能列表:\n" +"[MAIN/M]:主菜单\n" +"[QUERY/Q]:查看全部女神的信息\n" +"[GET/G]:查看某位女神的详细信息\n" +"[ADD/A]:添加女神信息\n" +"[UPDATE/U]:更新女神信息\n" +"[DELETE/D]:删除女神信息\n" +"[SEARCH/S]:查询女神信息(根据姓名、手机号来查询)\n" +"[EXIT/E]:退出女神禁区\n" +"[BREAK/B]:退出当前功能,返回主菜单";private static final String OPERATION_MAIN="MAIN";private static final String OPERATION_QUERY="QUERY";private static final String OPERATION_GET="GET";private static final String OPERATION_ADD="ADD";private static final String OPERATION_UPDATE="UPDATE";private static final String OPERATION_DELETE="DELETE";private static final String OPERATION_SEARCH="SEARCH";private static final String OPERATION_EXIT="EXIT";private static final String OPERATION_BREAK="BREAK";public static void main(String[] args) {System.out.println(CONTEXT);//怎么保持程序一直运行Scanner scan=new Scanner(System.in);Goddess goddess=new Goddess();GoddessAction action=new GoddessAction();String prenious=null;Integer step=1;while(scan.hasNext()){String in=scan.next().toString();if(OPERATION_EXIT.equals(in.toUpperCase())||OPERATION_EXIT.substring(0, 1).equals(in.toUpperCase())){System.out.println("您已成功退出女神禁区。");break;}else if(OPERATION_QUERY.equals(in.toUpperCase())||OPERATION_QUERY.substring(0, 1).equals(in.toUpperCase())){try {List<Goddess> list=action.query();for (Goddess go : list) {System.out.println(go.getId()+",姓名:"+go.getUser_name());}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}else if(OPERATION_ADD.equals(in.toUpperCase())||OPERATION_ADD.substring(0, 1).equals(in.toUpperCase())||OPERATION_ADD.equals(prenious)){prenious=OPERATION_ADD;//新增女神if(1==step){System.out.println("请输入女神的[姓名]");}else if(2==step){goddess.setUser_name(in);System.out.println("请输入女神的[年龄]");}else if(3==step){goddess.setAge(Integer.valueOf(in));System.out.println("请输入女神的[生日],格式如:yyyy-MM-dd");}else if(4==step){SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");Date birthday=null;try {birthday = sf.parse(in);goddess.setBirthday(birthday);System.out.println("请输入女神的[邮箱]");} catch (ParseException e) {e.printStackTrace();System.out.println("您输入的格式有误,请重新输入");step=3;}}else if(5==step){goddess.setEmail(in);System.out.println("请输入女神的[手机号]");}else if(6==step){goddess.setMobile(in);try {action.add(goddess);System.out.println("新增女神成功");} catch (Exception e) {e.printStackTrace();System.out.println("新增女神失败");}}if(OPERATION_ADD.equals(prenious)){step++;}}else{System.out.println("您输入的值为:"+in);}}}}








0 0
原创粉丝点击