mvc设计模式与三层架构

mvc与三层架构 

1.什么是mvc设计模式


Java Web
项⽬时会发现,一个中型或者大型项目随着代码的增多,会发现:代码既可以写在
src目
录下,也可以写在WebContent目
录下。
src
下可以建很多包,
WebContent
下可以建很多文件夹。
所以问题就来了:一个新的类到底往哪个目录下的哪个文件夹里写?
此时解决办法就是:需要一个模式去规范,到底哪个类该往哪里写

M(Model) 模型 : 应用程序的核心功能,管理这个模块中用的数据和值(bean,dao); 

V(View )视图: 视图提供模型的展示,管理模型如何显示给用户,它是应用程序的外观(jsp/html

C(Controller)
控制器
: 对用户的输入做出的反应,管理用户和视图的交互,也是连接模型和视图的枢纽(
servlet/service)
MVC用
于将
web

UI
)层进行职责解耦
说明
:mvc
设计模式
(
不属于
23
种设计模式
)

2.三层架构 

 3.三层架构和MVC的区别与联系

准备工作

1.包结构

2.导入jar包

配置Tomcat 

 简化地址栏信息

工具类util:DruidUtil

package util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtil {

    private static DataSource ds;
    static{
        try {
            Properties ppt = new Properties();
            ppt.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(ppt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 从连接池中取出一个连接给用户
     * @return
     */
    public static Connection getConnection(){
        try {
            return ds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }


    public static void close(Connection conn, Statement state, ResultSet rs){
        try {
            rs.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        try {
            state.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        try {
            conn.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }
}

属性配置文件 druid.properties

url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=10
minIdle=5
maxWait=3000

 一个请求的流程

一:MVC之Model开发

 beam包:实体类Student

package bean;
//实体类包=主要存放数据库对应的实体类
//类名=表名
//列名=属性名
//实体类包括:属性,构造方法(无参,全参),setter/getter
//属于Model(M)
public class Student {
    private Integer stuid;
    private String stuname;
    private Integer age;
    private String sex;
    //无参构造方法
    public Student() {
    }
    //全参构造方法
    public Student(Integer stuid, String stuname, Integer age, String sex) {
        this.stuid = stuid;
        this.stuname = stuname;
        this.age = age;
        this.sex = sex;
    }

    public Integer getStuid() {
        return stuid;
    }

    public void setStuid(Integer stuid) {
        this.stuid = stuid;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuid=" + stuid +
                ", stuname='" + stuname + ''' +
                ", age=" + age +
                ", sex='" + sex + ''' +
                '}';
    }
}

dao包:StudentDao接口

package dao;

import bean.Student;

import java.util.List;

//实体类名+Dao=当前类名
public interface StudentDao {
    //定义操作数据库的方法
    //查询全部方法
    public List<Student> getAll();
}

dao包:impl子包: StudentDaoImpl接口实现类

package dao.impl;

import bean.Student;
import dao.StudentDao;
import util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//接口名+impl=当前类名
public class StudentDaoImpl extends DruidUtil implements StudentDao {
    @Override
    public List<Student> getAll() {
        Connection connection =null;
        PreparedStatement preparedStatement =null;
        ResultSet resultSet=null;
        List list=new ArrayList();
        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement("select * from  student");
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                Student student = new Student();
                student.setStuid(resultSet.getInt("stuid"));
                student.setStuname(resultSet.getString("stuname"));
                student.setAge(resultSet.getInt("age"));
                student.setSex(resultSet.getString("sex"));
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(connection,preparedStatement,resultSet);
        }
        return list;
    }
}

二:MVC之Controlle开发

service包 :StudentService接口

package service;

import bean.Student;

import java.util.List;

//bean类名+Service=当前类名
//Service层主要定义业务逻辑,现阶段主要实现调取dao层
public interface StudentService {
    //查询全部方法
    public List<Student> getAll();
}

service包 :impl子包:StudentServiceImpl接口实现类

package service.impl;

import bean.Student;
import dao.StudentDao;
import dao.impl.StudentDaoImpl;
import service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao=new StudentDaoImpl();
    @Override
    public List<Student> getAll() {
        return studentDao.getAll();
    }
}

servlet包 :StudentServlet处理类处理请求

package servlet;

import bean.Student;
import service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

//C -controller 控制层
@WebServlet(urlPatterns = "/getstus")
public class StudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接参数(接收请求参数)

        //写逻辑(调取service层方法)
        StudentServiceImpl studentService=new StudentServiceImpl();
        List<Student> getAll=studentService.getAll();
        //返结果(跳转页面)
        //后台传递数据给前台
        req.setAttribute("stulist",getAll);
        req.getRequestDispatcher("/show.jsp").forward(req,resp);
    }
}

 三:MVC之View开发

index.jsp页面  

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$Title$</title>
</head>
<body>
<a href="getstus">查询学生列表</a>
</body>
</html>

 show.jsp页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>show.jsp</h1>
<table border="" width="500px" bgcolor="aqua">
    <tr>
        <td>id</td>
        <td>name</td>
        <td>age</td>
        <td>sex</td>
    </tr>
    <c:forEach items="${stulist}" var="stu">
        <tr>
            <td>${stu.stuid}</td>
            <td>${stu.stuname}</td>
            <td>${stu.age}</td>
            <td>${stu.sex==1?"男":"女"}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

测试结果 

 

前后端分离技术(了解)

 

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>