MVC&三层架构

MVC & 三层架构

项目结构

--projectName
	--src
		--com
			--fc
				--dao
					--impl
				--bean
				--filter
				--service
					--impl
				--controller
				--test
				--util
	--web
		--WEB-INF
			--classes
			--lib
		--after
		--before
		--css
		--js
		--fonts
		--images

相关类别描述

类别描述
projectName项目名称
src存放Java代码
com.fc包名
bean存放实体类
dao数据层,用于执行与数据库相关的操作
dao.impl数据层的接口实现类
service业务层,用于业务的处理【都是接口】
service.impl业务层的接口实现类
controller控制层,用于和前端页面进行交互【Servlet】
util工具类
filter过滤器
listener监听器
test测试类
webweb 相关资源
WEB-INF无法通过 URL 访问的文件夹
classes存放编译过后的字节码文件
lib存放 jar 包
after存放台 html/jsp 页面
before存放前台 html/jsp 页面
css存放 css 文件资源
js存放 js 文件资源
fonts存放字体资源
images存放图片资源

没有涉及的可以不写

分页

分页相关参数

page
pageNo当前页
pageCount总页数,总数据量除以每页显示的条数(不够再加1)
pageSize每页显示多少条数据,用于限定查询中的条件
start每页中第一条数据(pageNo - 1 * pageSize),用于限定查询中的条件
totalCount总数据量,查询全部的结果
dataList每页中的所有数据,限定查询的结果
上一页当前页 - 1,从第一页起
下一页当前页 + 1,到最后一页为止
首页当前页 = 1
尾页总页数 pageCount

分页信息实体类

/**
 * 分页信息实体类,包含一些通用的参数
 *
 * @param <T> 泛型,对应实体类的类型
 */
public class PageInfo<T> {
    // 总页数
    private int pageCount;
    // 数据总条数
    private int totalCount;
    // 每页显示的条数
    private int pageSize;
    // 当前页
    private int pageNo;
    // 当前页中的数据,可能有多条,声明一个List集合,泛型为对应实体类的类型
    private List<T> list;

    public PageInfo() {
    }

    public PageInfo(int totalCount, int pageSize, int pageNo, List<T> list) {
        this.totalCount = totalCount;
        this.pageSize = pageSize;
        this.pageNo = pageNo;
        this.list = list;
        // 如果数据总数能够整除每页显示的条数
        if (totalCount % pageSize == 0) {
            // 总页数等于数据总条数除以每页显示多少条数据
            this.pageCount = totalCount / pageSize;
        } else {
            // 无法整除,再增加一页
            this.pageCount = totalCount / pageSize + 1;
        }
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "PageInfo{" +
                "pageCount=" + pageCount +
                ", totalCount=" + totalCount +
                ", pageSize=" + pageSize +
                ", pageNo=" + pageNo +
                ", list=" + list +
                '}';
    }
}

dao 层接口

/**
 * 学生数据操作接口,用来对数据库进行操作
 */
public interface StudentDao<T> {
    /**
     * 获取学生表中的数据的总量
     *
     * @return 数据总条数
     */
    int getTotalCount();

    /**
     * 获取每页显示的数据
     *
     * @param start 从第几条数据开始
     * @param pageSize 每页显示多少条数据
     * @return 返回包含指定页中所有数据的集合
     */
    List<T> getStudentsByPage(int start, int pageSize);
}

dao 层接口实现类

/**
 * 学生数据操作接口实现类
 */
public class StudentDaoImpl implements StudentDao {
    // 获取核心类对象
    private QueryRunner queryRunner = new QueryRunner();

    // 获取数据库连接
    private Connection connection = JdbcUtilsOnC3P0.getConnection();

    // 获取表中的总数量
    @Override
    public int getTotalCount() {
        // 准备SQL语句
        String sql = "select * from student";

        // 提取结果集合
        List<Student> list = null;

        try {
            // 执行SQL语句并获取List集合
            list = queryRunner.query(connection, sql, new BeanListHandler<>(Student.class));
        } catch (SQLException e) {
            e.printStackTrace();
            list = new ArrayList<>();
        }

        // 返回集合的长度
        return list.size();
    }

    /**
     * 获取每页中的数据
     *
     * @param start 从第几条数据开始
     * @param pageSize 每页显示多少条数据
     * @return 返回一个集合,包含一页中的所有数据
     */
    @Override
    public List<Student> getStudentsByPage(int start, int pageSize) {

        // 准备SQL语句
        String sql = "select * from student limit ?, ?";

        // 准备参数
        Object[] params = {start, pageSize};

        // 提取集合
        List<Student> list = null;

        try {
            // 执行SQL语句并获取包含数据的集合
            list = queryRunner.query(connection, sql, new BeanListHandler<>(Student.class), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 返回集合
        return list;
    }
}

业务层接口

/**
 * 学生业务接口,用来实现业务逻辑
 */
public interface StudentService<T> {

    /**
     * 此方法用于获取分页信息
     *
     * @param pageNo 当前页码
     * @param pageSize 每页显示多少条信息
     * @return 返回分页信息实体类
     */
    PageInfo<T> findStudentsByPage(String pageNo, int pageSize);
}

业务层接口实现类

/**
 * 学生业务接口实现类
 */
public class StudentServiceImpl implements StudentService {
    @Override
    public PageInfo<Student> findStudentsByPage(String pageNo, int pageSize) {
        // 获取学生数据层操作对象
        StudentDao studentDao = new StudentDaoImpl();

        // 通过数据层操作对象获取总数据量
        int totalCount = studentDao.getTotalCount();

        // 如果当前页码不存在
        if (pageNo == null) {
            // 默认使用第一页
            pageNo = "1";
        }

        // String类型转化为int类型
        int currentPage = Integer.parseInt(pageNo);

        // 获取每一页中的第一条数据
        int start = (currentPage - 1) * pageSize;

        // 通过数据操作对象获取每一页要显示的数据
        List<Student> students = studentDao.getStudentsByPage(start, pageSize);

        // 声明分页信息对象,将总数据量,每页显示多少条数据,当前的页数,当前页的数据存入分页信息中
        PageInfo<Student> studentPageInfo = new PageInfo<>(totalCount, pageSize, currentPage, students);

        // 返回分页信息对象
        return studentPageInfo;
    }
}

控制层 Servlet

/**
 * 控制层,通过Servlet与前端进行交互
 */
@WebServlet("/page")
public class FIndByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取显示的页数
        String pageNo = req.getParameter("pageNo");

        // 声明每页显示的条数
        int pageSize = 5;

        // 获取学生业务对象
        StudentService studentService = new StudentServiceImpl();

        // 通过业务对象执行获取分析信息对象
        PageInfo<Student> pageInfo = studentService.findStudentsByPage(pageNo, pageSize);

        // 设置请求对象的属性键值对
        req.setAttribute("pageInfo", pageInfo);

        // 转发到主页面
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>主页</title>
</head>
<body>
    <%--固定高度--%>
    <div style="height: 300px">
        <%--学生信息表,居中边框1px--%>
        <table border="1px" align="center">
            <%--表头--%>
            <caption><h1 align="center" style="color: greenyellow">学生信息表</h1></caption>
            <%--标题栏--%>
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>信息</th>
            </tr>

            <%--通过JSTL遍历学生信息--%>
            <c:forEach var="student" items="${pageInfo.list}">
                <%--通过EL表达式获取学生信息--%>
                <tr>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.age}</td>
                    <td>${student.gender}</td>
                    <td>${student.info}</td>
                </tr>
            </c:forEach>
        </table>
    </div>

    <%--form表单用来提交页码--%>
    <form action="page" method="get">
        <table align="right">
            <tr>
                <%--如果当前页为第一页,则首页和上一页设置无法选中--%>
                <c:if test="${pageInfo.pageNo == 1}">
                    <td><a href="javascript:return false;" style="text-decoration: none; color: orangered">首页</a></td>
                    <td><a href="javascript:return false;" style="text-decoration: none; color: orangered">上一页</a></td>
                </c:if>

                <%--如果当前不为第一页--%>
                <c:if test="${pageInfo.pageNo != 1}">
                    <%--设置首页直接跳转为第一页,传递pageNo为1--%>
                    <td><a href="page?pageNo=1" style="text-decoration: none">首页</a></td>
                    <%--设置上一页,传递pageNo为 当前页 - 1--%>
                    <td><a href="page?pageNo=${pageInfo.pageNo - 1}" style="text-decoration: none">上一页</a></td>
                </c:if>

                <%--遍历当前页数--%>
                <c:forEach var="pageNo" varStatus="pageStatus" begin="1" end="${pageInfo.pageCount}">
                    <%--如果是当前页,就设置不可点击--%>
                    <c:if test="${pageNo == pageInfo.pageNo}">
                        <td><input type="submit" name="pageNo" value="${pageNo}" disabled></td>
                    </c:if>

                    <%--非当前页设置可点击--%>
                    <c:if test="${pageNo != pageInfo.pageNo}">
                        <td><input type="submit" name="pageNo" value="${pageNo}"></td>
                    </c:if>
                </c:forEach>

                <%--如果当前页为最后一页,则尾页和下一页设置无法选中--%>
                <c:if test="${pageInfo.pageNo == pageInfo.pageCount}">
                    <td><a href="javascript:return false;" style="text-decoration: none; color: orangered">下一页</a></td>
                    <td><a href="javascript:return false;" style="text-decoration: none; color: orangered">尾页</a></td>
                </c:if>

                <%--如果当前不为最后一页--%>
                <c:if test="${pageInfo.pageNo != pageInfo.pageCount}">
                    <%--设置下一页,传递pageNo为 当前页 + 1--%>
                    <td><a href="page?pageNo=${pageInfo.pageNo + 1}" style="text-decoration: none">下一页</a></td>
                    <%--设置尾页直接跳转为最后一页,传递pageNo为总页数--%>
                    <td><a href="page?pageNo=${pageInfo.pageCount}" style="text-decoration: none">尾页</a></td>
                </c:if>

                <%--从分页信息中获取数据总数和总页数--%>
                <td>共${pageInfo.totalCount}条内容,共${pageInfo.pageCount}页</td>
            </tr>
        </table>
    </form>

</body>
</html>

文件上传

Servlet 可以与 HTML form 标签一起使用,来允许用户上传文件到服务器。上传的文件可以是文本文件或图像文件或任何文档。

Servlet 内置文件上传

Servlet3.1 开始支持文件上传,需要声明 @MutipartConfig 注解

常用 API

// 返回一个包含所有文件的集合
public Collection<Part> getParts();

// 获取上传的文件,如果文件不存在获取null
public Part getPart(String name);

步骤

1、在前端页面的form标签中声明 enctype="multipart/form-data" 属性,并声明input标签的类型为 file
2、编写Servlet并声明@MutipartConfig注解
3、获取文件对象
4、上传至指定路径

前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <form method="post" action="upload" enctype="multipart/form-data">
        文件上传:<input type="file" name="file">
        <input type="submit" value="上传">
    </form>
</body>
</html>

后端逻辑

@WebServlet("/upload")
// 声明文件上传所需要的注解
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从前端获取name属性对应的文件
        Part file = req.getPart("file");

        // 获取对应的请求头
        String head = file.getHeader("Content-Disposition");
        
        // 获取请求头中的文件名部分
        String fileName = head.substring(head.indexOf("filename=\"") + 10, head.lastIndexOf("\""));
        
        
        System.out.println(fileName);

        // 把文件写入到指定路径
        file.write("D:/apache-tomcat-8.5.37/webapps/images/" + fileName);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

FileUpload 文件上传组件

FileUpload 是 Apache 组织提供的免费上传组件。FileUpload 组件本身依赖于 Commons 组件包,此包中提供了大量开发类可作为 Java 的有力补充,在很多框架开发中都可以直接使用。

官方文档

http://commons.apache.org/proper/commons-fileupload/javadocs/api-release/index.htmls

需要导入两个jar包

commons-fileupload-1.4.jar
commons-io-2.8.0.jar

步骤

1、在前端页面的form标签中声明 enctype="multipart/form-data" 属性,并声明input标签的类型为 file
2、导包
3、声明Servlet

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form method="post" action="uploadByFileUpload" enctype="multipart/form-data">
    文件上传1:<input type="file" name="file">
    文件上传2:<input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

后台逻辑

@WebServlet("/uploadByFileUpload")
public class UploadByFileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建一个工厂类对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 创建文件上传对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置单个文件大小限制
        upload.setFileSizeMax(1024 * 1024 * 10);

        // 设置所有文件总和大小限制
        upload.setSizeMax(1024 * 1024 * 30);

        try {
            // 解析请求对象获取包含所有上传文件项的集合
            List<FileItem> list = upload.parseRequest(req);

            // 遍历所有文件项
            for (FileItem fileItem : list) {
                // 获取文件项的文件名并展示
                System.out.println(fileItem.getName());

                // 上传到指定路径中
                fileItem.write(new File("C:/Users/Buffer/Desktop", fileItem.getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值