JavaWeb三层架构

Posted itronion

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb三层架构相关的知识,希望对你有一定的参考价值。

三层架构主要分为dao层、service层、视图层

dao层-----------------主要是封装功能的实现方法

service层------------也称为业务逻辑处理层,主要是调用dao层并处理业务逻辑

视图层----------------也就是jsp、html页面展示数据、使数据可视化

 

其实三层架构是一种泛型意义,实际开发中不至于这三层;比如说还有实体类层,servlet层等等。三层架构主要是为了使开发中职责明确、代码有层次、易维护。

下面是JavaWeb项目三层架构详图

技术图片

代码部分:

dao层

技术图片BaseDao
package com.dao;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;

public class BaseDao {
    
    private static String Driver = "com.mysql.jdbc.Driver";    //mysql8 的写法不同,请自行百度
    private String User = "root";
    private String Password = "root";
    private String Url = "jdbc:mysql://localhost:3306/orderingsystem";

    private Connection conn = null;
    private PreparedStatement ptmt = null;
    private ResultSet rs = null;

    /**
     * 注册驱动
     */
    static {
        try {
            Class.forName(Driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Connection对象的方法
     *
     * @return
     */
    public void getConnection() {
        conn = null;
        try {
            conn = DriverManager.getConnection(Url, User, Password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 增删改
     *
     * @param sql
     */
    public int executeUpdate(String sql, Object[] param) {
        int result = 0;
        try {
            getConnection();// 注册驱动获取链接
            ptmt = conn.prepareStatement(sql);
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    ptmt.setObject(i + 1, param[i]);
                }
            }
            result = ptmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(); // 关闭资源
        }
        return result;
    }

    /**
     * 查
     *
     * @param sql
     * @return
     */
    public ResultSet executeQuery(String sql, Object[] param) {
        try {
            getConnection();
            ptmt = conn.prepareStatement(sql);
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    ptmt.setObject(i + 1, param[i]);
                }
            }
            rs = ptmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 关闭资源对象
     */
    public void closeAll() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                rs = null;
            }
        }
        if (ptmt != null) {
            try {
                ptmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                ptmt = null;
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                conn = null;
            }
        }
    }
}

技术图片
package org.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.entity.BookManage;

public class BookManageDao extends BaseDao {
    //A、编写查询方法,查询所有图书信息
    public List<BookManage> FindAll() {
        List<BookManage> list = new ArrayList<BookManage>();
        BookManage bm = null;
        String sql = "SELECT b_id,b_name,b_author,b_time,b_type FROM bookmanage;";
        ResultSet rs = executeQuery(sql, null);
        
        try {
            while (rs.next()) {
                bm = new BookManage();
                bm.setB_id(rs.getInt("b_id"));
                bm.setB_name(rs.getString("b_name"));
                bm.setB_author(rs.getString("b_author"));
                bm.setB_time(rs.getString("b_time"));
                bm.setB_type(rs.getInt("b_type"));
                list.add(bm);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            closeAll();
        }
        return list;
    }
    
    //B、编写添加方法,新增图书信息
    public int AddBook(BookManage bm) {
        String sql = "INSERT INTO bookmanage(b_name,b_author,b_time,b_type)VALUES(?,?,?,?)";
        Object[] param = {bm.getB_name(),bm.getB_author(),bm.getB_time(),bm.getB_type()};
        return executeUpdate(sql, param); 
    }
    
    //C、编写删除方法,删除指定的图书信息
    public int DelBook(int id) {
        String sql = "DELETE FROM bookmanage WHERE b_id=?";
        Object[] param = {id};
        return executeUpdate(sql, param);
    }
    
}
BookManageDao

实体类

技术图片
package org.entity;

public class BookManage {
    private int b_id;
    private String b_name;
    private String b_author;
    private String b_time;
    private int b_type;

    public int getB_id() {
        return b_id;
    }

    public void setB_id(int b_id) {
        this.b_id = b_id;
    }

    public String getB_name() {
        return b_name;
    }

    public void setB_name(String b_name) {
        this.b_name = b_name;
    }

    public String getB_author() {
        return b_author;
    }

    public void setB_author(String b_author) {
        this.b_author = b_author;
    }

    public String getB_time() {
        return b_time;
    }

    public void setB_time(String b_time) {
        this.b_time = b_time;
    }

    public int getB_type() {
        return b_type;
    }

    public void setB_type(int b_type) {
        this.b_type = b_type;
    }

}
BookManage

service层

技术图片
package org.service;

import java.util.List;
import org.dao.BookManageDao;
import org.entity.BookManage;

public class BookManageService {
    // A、编写查询方法,查询所有图书信息
    public List<BookManage> FindAll() {
        return new BookManageDao().FindAll();
    }

    // B、编写添加方法,新增图书信息
    public int AddBook(BookManage bm) {
        return new BookManageDao().AddBook(bm);
    }

    // C、编写删除方法,删除指定的图书信息
    public int DelBook(int id) {
        return new BookManageDao().DelBook(id);
    }
}
BookManageService

servlet层

技术图片
package org.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 org.entity.BookManage;
import org.service.BookManageService;

@WebServlet("/add")
public class Add extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // -------------设置字符集编码------------------
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");

        // -------------获取数据-----------------------
        String b_name = req.getParameter("b_name");
        String b_author = req.getParameter("b_author");
        String b_time = req.getParameter("b_time");
        String b_type = req.getParameter("b_type");
        
        //--------------测试数据------------------------
//        System.out.println(b_name);
//        System.out.println(b_author);
//        System.out.println(b_time);
//        System.out.println(b_type);

        // -------------添加数据----------------------
        BookManage bm = new BookManage();
        bm.setB_name(b_name);
        bm.setB_time(b_time);
        bm.setB_type(Integer.parseInt(b_type));
        bm.setB_author(b_author);

        BookManageService bs = new BookManageService();
        int result = bs.AddBook(bm);

        // --------------响应数据---------------------
        PrintWriter out = resp.getWriter();
        if (result > 0) {
            out.print(true);
        } else {
            out.print(false);
        }
        out.flush();
        out.close();
    }
}
Add
技术图片
package org.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 org.service.BookManageService;

@WebServlet("/del")
public class Del extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //-------------设置字符集编码------------------
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        
        //-------------获取id-------------------------
        int id = Integer.parseInt(req.getParameter("id"));
        
        //-------------删除数据-----------------------
        BookManageService bm = new BookManageService();
        int result = bm.DelBook(id);
        
        //-------------响应结果------------------------
        PrintWriter out = resp.getWriter();
        if (result > 0) {
            out.print(true);
        } else {
            out.print(false);
        }
        out.flush();
        out.close();
    }
}
Del
技术图片
package org.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 org.entity.BookManage;
import org.service.BookManageService;

@WebServlet("/loaddata")
public class Loaddata extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //-------------设置字符集编码------------------
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        
        //-------------拼接html-----------------------
        List<BookManage> list = new BookManageService().FindAll();
        StringBuffer newList = new StringBuffer("");
        newList.append("<tr><td colspan=‘5‘><h2>图书信息</h2></td></tr>");
        newList.append("<tr><td>图书名称</td><td>图书作者</td><td>购买时间</td><td>图书分类</td><td>操作</td></tr>");
        if (list != null) {
            for (BookManage bm : list) {
                newList.append("<tr><td>"+bm.getB_name()+"</td><td>"+bm.getB_author()+"</td><td>"+bm.getB_time()+"</td><td>"+bm.getB_type()+"</td><td><a href=‘#‘ onclick=‘delbook("+bm.getB_id()+")‘>删除</a></td></tr>");
            }
        }
        
        //------------响应数据------------------------
        PrintWriter out = resp.getWriter();
        out.print(newList);
        out.flush();
        out.close();
    }

}
Loaddata

视图层

技术图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="css/add.css" />
</head>
<body>
    <form action="" method="post" id="for">
        <table width="30%" align="center" id="tb">
            <tr>
                <td colspan="3">
                    <h2>新增图书信息</h2>
                </td>
            </tr>
            <tr>
                <td>图书名称:</td>
                <td><input type="text" name="b_name" id="b_name" value="" /></td>
                <td></td>
            </tr>
            <tr>
                <td>图书作者:</td>
                <td><input type="text" name="b_author" id="b_author" value="" /></td>
                <td></td>
            </tr>
            <tr>
                <td>购买日期:</td>
                <td><input type="text" name="b_time" id="b_time" value="" /></td>
                <td>yyyy-MM-DD格式</td>
            </tr>
            <tr>
                <td>图书类别:</td>
                <td><select name="b_type" id="b_type">
                        <option value="0">请选择所属分类</option>
                        <option value="1">计算机/软件</option>
                        <option value="2">小说/文摘</option>
                        <option value="3">杂项</option>
                </select></td>
                <td></td>
            </tr>
            <tr>
                <td colspan="3"><input type="button" value="增加图书"
                    align="center" id="btn" /></td>
            </tr>

        </table>
    </form>
    <script src="js/jQuery3.5.js"></script>
    <script type="text/javascript">
        $("#btn").click(function() {
            //非空验证
            var b_name = $("#b_name").val();
            var b_author = $("#b_author").val();
            var b_time = $("#b_time").val();
            var b_type = $("#b_type").val();
            var dateFormat =/^(d{4})-(d{2})-(d{2})$/;    //日期正则表达式
            
            if (b_name == "" || b_name == null) {
                alert("请输入书名!");
            } else if (b_author == "" || b_author == null) {
                alert("请输入作者!");
            }else if (b_time == "" || b_time == null) {
                alert("请输入时间!");
            }else if (b_type == 0 || b_name == null) {
                alert("请选择书的类别");
            }else if (!(dateFormat.test(b_time))) {
                alert("日期格式不正确");
            }else {
                var info = $("#for").serialize();
                $.ajax({
                    url : "add",
                    data : info,
                    dataType : "text",
                    type : "POST",
                    success : callback
                });
            }
        });

        function callback(data) {
            if (data == "true") {
                alert("添加成功!");
                location.href = "index.jsp";
            } else {
                alert("添加失败!");
            }
        }
    </script>
</body>
</html>
add.jsp
技术图片
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
    <div id="dv">
        <table border="1" width="100%" align="center" id="tb">
        </table>
        <a href="add.jsp">新增图书信息</a>
    </div>
    <script src="js/jQuery3.5.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#tb").load("loaddata");
        });

        function delbook(id) {
            var isDel = window.confirm("确定要删除嘛?");
            if (isDel) {
                $.ajax({
                    url : "del",
                    data : "id=" + id,
                    dataType : "text",
                    type : "POST",
                    success : callback
                });
            }
        }

        function callback(data) {
            if (data == "true") {
                alert("删除成功!");
                $("#tb").load("loaddata");//刷新数据
            } else {
                alert("删除失败!");
            }
        }
    </script>
</body>
</html>
index.jsp

 

代码仅供展示参考,使易理解!

以上是关于JavaWeb三层架构的主要内容,如果未能解决你的问题,请参考以下文章

MVC设计模式与JavaWeb的三层架构

Javaweb的MVC模式和三层架构(框架了解)

JavaWeb之MVC三层架构

JavaWeb三层架构

JavaWeb 之 三层架构:软件设计架构

JavaWeb.三层架构项目集成