MVC框架简介

MVC全名是Model View Controller,是模型(Model)-视图(View)-控制器(Controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑

  • Model(模型)表示应用程序核心(比如数据库记录列表)
  • View(视图)显示数据(数据库记录)
  • Controller(控制器)处理输入(写入数据库记录)

JavaSE实例

创建数据库

模型类

package model;

public class Student {

    private Integer StuId;
    private String  stuName;
    private Integer stuAge;
    private String  stuTel;
    private String  stuAddress;
    private Integer groupId;

    public Integer getStuId() {
        return StuId;
    }

    public void setStuId(Integer stuId) {
        StuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public Integer getStuAge() {
        return stuAge;
    }

    public void setStuAge(Integer stuAge) {
        this.stuAge = stuAge;
    }

    public String getStuTel() {
        return stuTel;
    }

    public void setStuTel(String stuTel) {
        this.stuTel = stuTel;
    }

    public String getStuAddress() {
        return stuAddress;
    }

    public void setStuAddress(String stuAddress) {
        this.stuAddress = stuAddress;
    }

    public int getGroupId() {
        return groupId;
    }

    public void setGroupId(Integer groupId) {
        this.groupId = groupId;
    }
}

JDBC工具类

/*
使用MySQL8.x以及8.x驱动
数据库名:school
数据表名:student
Java版本:1.8
*/

package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCUtils {

    public static Connection getConnection() {
        String driverName = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/school? useUnicode=true&characterEncoding=gb2312";
        String user = "root";
        String password = "root";
        Connection con = null;

        try {

            Class.forName(driverName);
            con = DriverManager.getConnection(url, user, password);
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * 关闭连接
     */
    public static void free(ResultSet rs, Statement sta, Connection con) {
        try {
            if (null != rs) {
                rs.close();
                rs = null;
            }

            if (null != sta) {
                sta.close();
                sta = null;
            }

            if (null != con) {
                con.close();
                con = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

DAO接口类

package dao;

import model.Student;
import java.util.Set;

public interface StudentDAO {

    int addStudent(Student student) ;

    int deleteStudent(String name);

    int updateStudent(String name);

    Student findStudent(String name);

    Set<Student> findAll();
}

DAO实现类(DAO层)

package dao;

import model.Student;
import utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

public class ConcreteStudentDao implements StudentDAO {

    //删除一个学生
    public int deleteStudent(String name) {
        Connection con = null;
        PreparedStatement ps = null;
        int i = 0;
        try {
            con = JDBCUtils.getConnection();
            String sql = "delete from student where stuName =?";
            ps = con.prepareStatement(sql);
            ps.setString(1, name);

            i = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.free(null, ps, con);
        }

        return i;
    }

    //修改一个学生
    public int updateStudent(String name) {
        Connection con = null;
        PreparedStatement ps = null;
        int i = 0;
        try {
            con = JDBCUtils.getConnection();
            String sql = "update student set stuAge=stuAge+1  where stuName =?";
            ps = con.prepareStatement(sql);
            ps.setString(1, name);

            i = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.free(null, ps, con);
        }

        return i;
    }

    //查询所有
    public Set<Student> findAll() {
        Connection con = null;
        PreparedStatement ps = null;
        Student stu = null;
        ResultSet rs = null;
        Set<Student> set = null;
        try {
            con = JDBCUtils.getConnection();
            String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student";
            ps = con.prepareStatement(sql);

            set = new HashSet<Student>();
            rs = ps.executeQuery();

            while (rs.next()) {
                stu = new Student();

                stu.setStuName(rs.getString(1));
                stu.setStuAge(rs.getInt(2));
                stu.setStuTel(rs.getString(3));
                stu.setStuAddress(rs.getString(4));
                stu.setGroupId(rs.getInt(5));

                set.add(stu);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.free(rs, ps, con);
        }

        return set;
    }


    @Override
    public int addStudent(Student student) {
        Connection con = null;
        PreparedStatement ps = null;
        int i = 0;
        try {
            con = JDBCUtils.getConnection();
            String sql = "insert into student(stuName,stuAge,stuTel,stuAddress,groupId) values(?,?,?,?,?)";
            ps = con.prepareStatement(sql);

            ps.setString(1, student.getStuName());
            ps.setInt(2, student.getStuAge());
            ps.setString(3, student.getStuTel());
            ps.setString(4, student.getStuAddress());
            ps.setInt(5, student.getGroupId());

            i = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("失败");
        } finally {
            JDBCUtils.free(null, ps, con);
        }
        return i;
    }

    @Override
    public Student findStudent(String name) {
        Connection con = null;
        PreparedStatement ps = null;
        Student stu = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();
            String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student where stuName =?";
            ps = con.prepareStatement(sql);
            ps.setString(1, name);

            rs = ps.executeQuery();
            stu = new Student();
            while (rs.next()) {
                stu.setStuName(rs.getString(1));
                stu.setStuAge(rs.getInt(2));
                stu.setStuTel(rs.getString(3));
                stu.setStuAddress(rs.getString(4));
                stu.setGroupId(rs.getInt(5));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.free(rs, ps, con);
        }

        return stu;
    }

}

服务层

package service;

import dao.ConcreteStudentDao;
import dao.StudentDAO;
import model.Student;

import java.util.Set;

public class StudentService {

    StudentDAO sd = new ConcreteStudentDao();

    public int add(Student student)
    {
        return this.sd.addStudent(student);
    }

    public int delete(String name)
    {
        return this.sd.deleteStudent(name);
    }

    public int update(String name)
    {
        return this.sd.updateStudent(name);
    }

    public Student find(String name)
    {
        return this.sd.findStudent(name);
    }

    public Set<Student> findAll()
    {
        return this.sd.findAll();
    }
}

View(表现层)

package view;

import model.Student;
import service.StudentService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class StartJFrame extends JFrame {

    final Font font = new Font("黑体",Font.PLAIN,30);

    private JButton add = new JButton("增加");
    private JButton del = new JButton("删除");
    private JButton upd = new JButton("修改");
    private JButton fin = new JButton("查询");

    private JLabel stuName = new JLabel("姓名");
    private JLabel stuAge = new JLabel("年龄");
    private JLabel stuTel = new JLabel("电话");
    private JLabel stuAddress = new JLabel("国家");
    private JLabel groupId = new JLabel("组");

    private JTextField Tname = new JTextField(10);
    private JTextField Tage = new JTextField(10);
    private JTextField Ttel = new JTextField(10);
    private JTextField Taddress = new JTextField(10);
    private JTextField Tgroup = new JTextField(10);

    private JPanel jbuttonpanel = new JPanel();
    private JPanel namep = new JPanel();
    private JPanel agep = new JPanel();
    private JPanel telp = new JPanel();
    private JPanel addressp = new JPanel();
    private JPanel groupidp = new JPanel();

    private String name;
    private String age;
    private String tel;
    private String address;
    private int groupid;

    private Set<Student> set = new HashSet<Student>();

    public StartJFrame(){

        this.setTitle("增删改查");
        this.setSize(800,600);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        this.setLayout(new GridLayout(2,5));

        addbutton();
        addAction();
        addJPanel();


        this.setVisible(true);

    }

    public void addbutton(){

        add.setFont(font);
        del.setFont(font);
        upd.setFont(font);
        fin.setFont(font);

        jbuttonpanel.add(add);
        jbuttonpanel.add(del);
        jbuttonpanel.add(upd);
        jbuttonpanel.add(fin);
        this.add(jbuttonpanel);
    }

    public void addAction(){
        Student stu = new Student();
        StudentService ss = new StudentService();

        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("单击了添加");
                try{
                    name = Tname.getText();
                    age  = Tage.getText();
                    tel  = Ttel.getText();
                    address = Taddress.getText();
                    groupid = Integer.parseInt(Tgroup.getText());

                    stu.setStuName(name);
                    stu.setStuTel(tel);
                    stu.setStuAge(Integer.parseInt(age));
                    stu.setStuAddress(address);
                    stu.setGroupId(groupid);

                    ss.add(stu);
                }
                catch (Exception e1){
                    System.out.println("错误");
                }

                set = ss.findAll();

                Iterator<Student> iterator = set.iterator();

                while(iterator.hasNext()){
                    Student student = iterator.next();
                    System.out.println(student.getStuName() +" " +student.getStuAge()+" "+student.getStuTel()+" "+student.getStuAddress()+" "+student.getGroupId());
                }
            }
        });

        del.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("单击了删除");
                name = Tname.getText();
                int i = ss.delete(name);
                if(i==0){
                    System.out.println("未找到需要删除的内容");
                }
                else{
                    System.out.println("删除成功");
                }
                System.out.println(i);
                set = ss.findAll();

                Iterator<Student> iterator = set.iterator();

                while(iterator.hasNext()){
                    Student student = iterator.next();
                    System.out.println(student.getStuName() +" " +student.getStuAge()+" "+student.getStuTel()+" "+student.getStuAddress()+" "+student.getGroupId());
                }
            }
        });

        fin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("单击了查找");
                name = Tname.getText();
                if(!name.equals("")){
                    Student student = ss.find(name);
                    Tage.setText(String.valueOf(student.getStuAge()));
                    Ttel.setText(student.getStuTel());
                    Taddress.setText(student.getStuAddress());
                    Tgroup.setText(String.valueOf(student.getGroupId()));
                    System.out.println(student.getStuName() +" " +student.getStuAge()+" "+student.getStuTel()+" "+student.getStuAddress()+" "+student.getGroupId());
                }
            }
        });

        upd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("单击了修改");

                name = Tname.getText();
                ss.update(name);

                set = ss.findAll();

                Iterator<Student> iterator = set.iterator();

                while(iterator.hasNext()){
                    Student student = iterator.next();
                    System.out.println(student.getStuName() +" " +student.getStuAge()+" "+student.getStuTel()+" "+student.getStuAddress()+" "+student.getGroupId());
                }

            }
        });

    }

    public void addJPanel(){

        stuName.setFont(font);
        Tname.setFont(font);
        namep.add(stuName);
        namep.add(Tname);

        stuAge.setFont(font);
        Tage.setFont(font);
        agep.add(stuAge);
        agep.add(Tage);

        stuTel.setFont(font);
        Ttel.setFont(font);
        telp.add(stuTel);
        telp.add(Ttel);

        stuAddress.setFont(font);
        Taddress.setFont(font);
        addressp.add(stuAddress);
        addressp.add(Taddress);

        groupId.setFont(font);
        Tgroup.setFont(font);
        groupidp.add(groupId);
        groupidp.add(Tgroup);

        this.add(namep);
        this.add(agep);
        this.add(telp);
        this.add(addressp);
        this.add(groupidp);
    }
}

整体结构

  1. 用户输入数据时,用户只与视图(表现层)交互
  2. 此时视图(表现层)调用服务层的方法
  3. 服务层调用DAO层
  4. DAO层去和数据库进行访问操作
  5. 最后再一层层将数据返回给视图(表现层)


一只小菜鸡