第5章 MVC模式

MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式:

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

MVC 模式同时提供了对 HTML、CSS 和 JavaScript 的完全控制。
Model(模型)是应用程序中用于处理应用程序数据逻辑的部分。
  通常模型对象负责在数据库中存取数据,处理业务逻辑和事务控制。
  目前阶段主要是:JDBC程序和业务逻辑Java程序
View(视图)是应用程序中处理数据显示的部分。
  通常视图是依据模型数据创建,发起事件。
  目前阶段主要是:JSP,HTML等页面展示部分
Controller(控制器)是应用程序中处理用户交互的部分。
  通常控制器负责从视图读取数据,控制用户输入,处理事件。
  目前阶段主要是:Servlet
MVC 分层可以对代码解耦合,有助于管理复杂的应用程序,程序开发者可以在一个时间内专门关注一个方面。比如,UI可以在不依赖业务逻辑的情况下专注于视图设计。

MVC分层还可以带来复用的好处,同样逻辑的代码可以多次使用,比如登录的业务逻辑在正常登录和利用cookie免登录时都能用到,使用MVC模式将其做成一个Service中的方法避免了多次重复编写。而且后期需求变更维护也可以做到一次修改处处生效。

演示示例

代码关系图


登录代码关系图

1. DBUtil.java数据库连接工具类

public class DBUtil {

    private static String url;
    private static String username;
    private static String password;
    
    private DBUtil() {}
    
    static {
        // 1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //读取配置文件,并完成连接字符串
        Properties p = new Properties();
        try {
            p.load(DBUtil.class.getResourceAsStream("DBConfig.properties"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String ip = p.getProperty("IPAdress");
        String port = p.getProperty("port");
        String db = p.getProperty("database");
        String tz = p.getProperty("timezone");
        url = "jdbc:mysql://"+ip+":"+port+"/"+db+"?useUnicode=true&characterEncoding=utf-8&serverTimezone="+tz;
        username = p.getProperty("username");
        password = p.getProperty("password");
    }   
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }   
    public static void close(Connection conn, Statement pst, ResultSet rs) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
        if(pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    }
    public static void close(Connection conn, Statement pst) {
        close(conn, pst, null);
    }   
    public static void close(Connection conn) {
        close(conn, null, null);
    }   
    public static void close(Statement pst, ResultSet rs) {
        close(null, pst, rs);
    }
}

2.DBConfig.properties数据库连接配置文件

IPAdress=mysql数据库IP地址,本机可写localhost
port=mysql数据库端口号
database=mysql数据库名
username=账号
password=密码
timezone=时区,国内使用东8区:GMT%2B8

3.login.jsp用户登录页面(View 视图层)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form action="/20190520/login" method="post">
用户名:<input type="text" name="lname"><br>
密码:<input type="password" name="lpass"><br>
<input type="submit" value="提交">
</form>
</body>
</html>

4.LoginServlet.java登录处理Servlet(Controller 控制器)

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        //验证登录
        String lname = request.getParameter("lname");
        String lpass = request.getParameter("lpass");
            
        //调用service
        SystemService ss = new SystemService();
        EmployeesPO po = ss.login(lname, lpass);
            
        //跳转
        if(po != null) {
            session.setAttribute("online", po);
            response.sendRedirect("/20190520/main.jsp");
        }else {
            response.sendRedirect("/20190520/login.jsp");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

5.SystemService.java处理业务逻辑和事务控制(Model-Service 模型层-业务层)

public class SystemService {    
    private SystemDAO dao = new SystemDAO();    

    public EmployeesPO login(String lname, String lpass) {
        Connection conn = DBUtil.getConnection();
        EmployeesPO po = null;
        try {
            po = dao.getEmpByLnameAndLpass(conn, lname, lpass);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }
        return po;
    }
}

6.SystemDAO.java数据处理(Model-DAO 模型层-数据管理层)

public class SystemDAO {
    
    public EmployeesPO getEmpByLnameAndLpass(Connection conn, String lname, String lpass) throws Exception {
        String sql = "select * from employees where lname = ? and lpass = ?";       
        PreparedStatement pst = null;
        ResultSet rs = null;
        EmployeesPO po = null;
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1, lname);
            pst.setString(2, lpass);
            rs = pst.executeQuery();
            if(rs.next()) {
                po = new EmployeesPO();
                po.setEmpid(rs.getInt("empid"));
                po.setEname(rs.getString("ename"));
                po.setLname(rs.getString("lname"));
                po.setLpass(rs.getString("lpass"));
                po.setSex(rs.getInt("sex"));
                po.setBirthday(rs.getDate("birthday"));
                po.setDeptno(rs.getInt("deptno"));
            }       
        } catch (Exception e) {
            throw e;
        } finally {
            DBUtil.close(pst, rs);
        }
        return po;
    }
}

7.EmployeesPO.java(pojo类)

public class EmployeesPO {
    
    private int empid;
    private String ename;
    private String lname;
    private String lpass;
    private int sex;
    private Date birthday;
    private int deptno;
    
    public int getEmpid() {
        return empid;
    }
    public void setEmpid(int empid) {
        this.empid = empid;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getLname() {
        return lname;
    }
    public void setLname(String lname) {
        this.lname = lname;
    }
    public String getLpass() {
        return lpass;
    }
    public void setLpass(String lpass) {
        this.lpass = lpass;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public int getDeptno() {
        return deptno;
    }
    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ASP.NET MVC 是一个全新的Web应用框架 ASP.NET 代表支撑应用框架的技术平台,表明ASP.NET...
    JunChow520阅读 1,266评论 0 1
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,145评论 1 32
  • 传统模式下的开发MVCMVVM基于面向协议MVP的介绍MVP实战开发说在前面:相信就算你是个iOS新手也应该听说过...
    行走的菜谱阅读 3,200评论 1 5
  • 1. MVC框架 MVC全名是Model View Controller,是模型(model)-视图(view)-...
    码上行动阅读 117,585评论 11 62
  • 简介 MVC开始是存在于桌面程序中的,M是指业务模型,V是指用户界面,C则是控制器,使用MVC的目的是将M和V的实...
    lifeline丿毅阅读 838评论 0 4