A frame for MVC

本文通过一个具体实例探讨了MVC(模型-视图-控制器)架构的设计与实现,并对比了MVC与MVP(模型-视图- presenter)的区别。文中详细介绍了如何构建一个简易的MVC框架,包括模型(Model)、视图(View)和控制器(Controller)各部分的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    Last time, I tried to make a speech about how to design a MVC frame by oneself in our software club. However, Neo pointed out the
difference between MVC and MVP: in MVC, C will never know about the V and it will never modify the V.
Though I don't think we should care much about whether webwork&struts are MVC or MVP frames,but at east ,MVC isfunny. Is it right?
    And also, I have made my frame be more likely a MVC frame.
    We will need two jsp files, a java class as model, and a java class as control.

    Let's come to model first:
    The model is a simple javabean,in fact the base class Model have a field for view. But customer using it don't have to know that,
    they just need to define the fields which will be the data showing in the view.

     //configurate the interceptors
@InterceptorsRef(interceptors = {ExceptionInterceptor.class ,ModelInterceptor.class})
//point out control for the model;
@ControlRef(clazz =UserControl.class)
public class UserModel extends Model
{
    private User user = new User();//A javaBean User
    private String people = "";//people

    public String getPeople()
    {
        return people;
    }

    public void setPeople(String people)
    {
        this.people = people;
    }

 

    public User getUser()
    {
        return user;
    }

    public void setUser(User user)
    {
        this.user = user;
    }
}


    next is  the control class:


    public class UserControl extends Control
{
    private UserModel model;
    private Logger log = Logger.getLogger("debugLogger");

    public void setModel(Model model)  //you should set the data model into the control;
    {
        this.model = (UserModel) model;
    }


    public void process()
    {
        User user = model.getUser(); //get the User from the model
        Integer age = user.getUserAge();
        if (age != null)
        {
            age += 100;
            user.setUserAge(age);
        }
        user.setUserName(user.getUserName() + "+ processed");
        user.setUserTitle(user.getUserTitle() + "+ processed");//change the value of User
        model.setPeople(model.getPeople() + " processed");//change the value of people
        model.setResult(Result.jsp("result.jsp"));//change the result of the model
    }
}

    and then we will come to the view:
    
     the input view:

 <!--"UserModel" means the class name of the model, and "process" means which method  of the control will be invoked  -->
     <form action="UserModel-process.do" method="post">
    <table width="30%">
        <tr>
            <td>user name:<input type="text" name="user.userName"></td>
        </tr>
        <tr>
            <td>user age:<input type="text" name="user.userAge"></td>
        </tr>
        <tr>
            <td>user title:<input type="text" name="user.userTitle"></td>
        </tr>
        <tr>
            <td>people:<input type="text" name="people"></td>
        </tr>

        <tr>
            <td>
                <input type="submit" value="process">

            </td>
        </tr>
    </table>
</form>

      and then it will come to the result view:

        <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <%@ taglib uri="/WEB-INF/simple-property.tld" prefix="simple" %>
  <html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>Simple jsp page</title></head>
      <table>
          <tr>
              <td>user name:<br><font color="green"><simple:property  property="user.userName"/></font></td>
          </tr>
          <tr>
              <td>user age:<br><font color="green"><simple:property  property="user.userAge"/></font></td>
          </tr>
          <tr>
              <td>user title:<br><font color="green"><simple:property  property="user.userTitle"/></font></td>
          </tr>
          <tr>
              <td>people:<br><font color="green"><simple:property  property="people"/></font></td>
          </tr>
      </table>
</html>


    I don't think this kind of frame is a real MVC frame: the control will never modify the data of the view. and the view will never know the
control.
    And at least, we can easily tell that which's the model,which's the view,and which's the control.
    After I developed the frame, and tried to use it for sereval times. I found that, in fact, about struts:the model is the ActionForm,the control
is the Action, and the jsp files is the View. The difference is that, the model was put in the control,and the View directly specifies it's control.
Its design make it more easily to be used,but less clearly to be understand.

 

 


   
   

import tkinter as tk from tkinter import ttk, messagebox import json import os from datetime import datetime class PersonnelManagementSystem: def __init__(self, root): self.root = root self.root.title("人员信息管理系统") self.root.geometry("900x600") self.root.minsize(800, 500) # 设置中文字体 self.style = ttk.Style() self.style.configure(".", font=("SimHei", 10)) # 数据文件和存储 self.data_file = "personnel_data.json" self.personnel_data = self._load_data() # 创建UI self._create_ui() self._refresh_treeview() def _load_data(self): """加载或初始化数据""" try: if os.path.exists(self.data_file): with open(self.data_file, "r", encoding="utf-8") as f: return json.load(f) else: initial_data = self._create_initial_data() self._save_data(initial_data) return initial_data except Exception as e: messagebox.showerror("错误", f"加载数据失败: {e}") return [] def _save_data(self, data=None): """保存数据到文件""" try: with open(self.data_file, "w", encoding="utf-8") as f: json.dump(data or self.personnel_data, f, ensure_ascii=False, indent=2) except Exception as e: messagebox.showerror("错误", f"保存数据失败: {e}") def _create_initial_data(self): """创建初始示例数据""" now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") return [ {"id": 1, "name": "张三", "gender": "男", "age": 30, "phone": "13800138000", "email": "zhangsan@example.com", "address": "北京市朝阳区", "create_time": now, "update_time": now}, {"id": 2, "name": "李四", "gender": "女", "age": 25, "phone": "13900139000", "email": "lisi@example.com", "address": "上海市浦东新区", "create_time": now, "update_time": now}, {"id": 3, "name": "王五", "gender": "男", "age": 35, "phone": "13700137000", "email": "wangwu@example.com", "address": "广州市天河区", "create_time": now, "update_time": now} ] def _create_ui(self): """创建用户界面""" # 主框架 main_frame = ttk.Frame(self.root, padding=10) main_frame.pack(fill=tk.BOTH, expand=True) # 搜索区域 search_frame = ttk.Frame(main_frame) search_frame.pack(fill=tk.X, pady=5) ttk.Label(search_frame, text="搜索:").pack(side=tk.LEFT, padx=5) self.search_var = tk.StringVar() ttk.Entry(search_frame, textvariable=self.search_var, width=30).pack(side=tk.LEFT, padx=5) ttk.Button(search_frame, text="搜索", command=self._search_data).pack(side=tk.LEFT, padx=5) ttk.Button(search_frame, text="重置", command=self._refresh_treeview).pack(side=tk.LEFT) # 表格区域 tree_frame = ttk.Frame(main_frame) tree_frame.pack(fill=tk.BOTH, expand=True, pady=5) columns = ("id", "name", "gender", "age", "phone", "email", "address", "create_time", "update_time") self.tree = ttk.Treeview(tree_frame, columns=columns, show="headings", selectmode="browse") # 设置列标题和宽度 for col in columns: self.tree.heading(col, text=col.capitalize()) width = 100 if col != "id" else 50 self.tree.column(col, width=width, anchor=tk.CENTER) # 添加滚动条 scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=self.tree.yview) self.tree.configure(yscroll=scrollbar.set) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.tree.pack(fill=tk.BOTH, expand=True) # 按钮区域 button_frame = ttk.Frame(main_frame) button_frame.pack(fill=tk.X, pady=5) for text, command in [("添加", self._add_person), ("修改", self._edit_person), ("删除", self._delete_person), ("刷新", self._refresh_treeview)]: ttk.Button(button_frame, text=text, command=command).pack(side=tk.LEFT, padx=5) def _refresh_treeview(self, data=None): """刷新表格数据""" for item in self.tree.get_children(): self.tree.delete(item) for person in (data or self.personnel_data): self.tree.insert("", tk.END, values=[ person["id"], person["name"], person["gender"], person["age"], person["phone"], person["email"], person["address"], person["create_time"], person["update_time"] ]) def _search_data(self): """搜索数据""" keyword = self.search_var.get().strip().lower() if not keyword: self._refresh_treeview() return results = [p for p in self.personnel_data if any(keyword in str(val).lower() for val in p.values())] self._refresh_treeview(results) d的知识点
最新发布
06-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值