SpringMVC(五)图书管理系统登录|书籍展示功能,三层架构解析

本文基于SpringMVC实现图书管理系统的登录验证与书籍列表展示功能,采用Mock数据模拟后端响应;重点解析标准三层架构(Controller/Service/DAO)在项目中的落地实践,明确各层职责划分,并对比MVC与三层架构的异同。内容涵盖前端HTML/AJAX调用、后端接口设计(/user/login、/book/getList)、BookInfo实体建模及Lombok简化开发,为后续集成MyBatis与数据库奠定架构基础。

前言❤️❤️

hello hello💕,这里是洋不写bug~😄,欢迎大家点赞👍👍,关注😍😍,收藏🌹🌹
在SpringMVC(一)(二)(三)(四)博客中,解析了SpringMVC的基础知识,以及一些前后端交互的小案例,这篇博客解析的图书管理系统才算是一个真正的项目
当然,仅凭SpringMVC的内容,是没办法做出一个标准的图书管理系统的,因此这篇博客只会解析登录和列表展示功能,以及后端开发的三层架构,在后续知识解析完成后(Spring IoC和Mybatis),会再出一篇博客来详细解析图书管理系统🐵
在这里插入图片描述
🎆个人主页:洋不写bug的博客
🎆所属专栏:JavaEE进阶专栏
🎆铁汁们对于JavaEE进阶的各种常用核心语法,都可以在上面的JavaEE进阶专栏学习,专栏正在持续更新中🏀,有问题可以写在评论区或者私信我哦~

1,前端代码

前端代码博主已经上传到了git仓库上,铁汁们点击下面的链接就可以下载(”图书管理“目录是前端代码,其他目录是后续补充的完整代码)
git仓库下载链接

在这里插入图片描述


前端文件如下所示:

在这里插入图片描述



图书管理系统由四个页面组成(对应四个html文件),分别是登陆、图书列表展示、修改图书、添加图书,如下图:

图书列表部分的显示是前端代码中添加的测试项,现在这个只是静态页面,进行添加、修改、删除操作都是无效的

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2,登录

创建个Spring项目,Type选择Maven,命名为Spring-book-demo,依赖就添加个Spring Web和Lombok如下图:

在这里插入图片描述

在这里插入图片描述



项目创建好后,可以删除的只剩下.idea目录、src目录、pom.xml,如下图:

在这里插入图片描述



把前端文件都拷贝到static目录中

在这里插入图片描述



  • 登录的接口约定:路径为/user/login,请求参数为name和password,请求方法定义为Post(向服务器上传数据),服务器接收参数后进行验证,验证成功返回true,验证失败返回false

登录操作就是接收前端传来的name和password,调用StringUtils的hasLength方法,看name和password是否为空或者长度为0
验证逻辑先写死,匹配固定的字符串,后续解析数据库框架后,把这部分再补上(可以先在上面加个TODO注释,表示这部分后续会进行完善,这部分会高亮显示,最后很快就能定位到这里)

package org.example.springbookdemo;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class UserController {
    @RequestMapping("/login")
    public boolean login(String name,String password){
        if(!StringUtils.hasLength(name) || !StringUtils.hasLength(password)){
            return false;
        }

        //TODO,后续学习数据库后,这部分再完善上
        if("admin".equals(name) && "123456".equals(password)){
            return true;
        }
        return false;
    }
}



接着写下前端login.html中的login方法,使用ajax,验证成功就跳转到book_list.html,代码如下:

<script>
        function login() {
            $.ajax({
                url: "/user/login",
                type: "post",
                data: {
                    name: $("#userName").val(),
                    password: $("#password").val()
                },
                success: function (result){
                    if(result){
                        //密码正确
                        location.href = "book_list.html";
                    }else {
                        alert("密码错误");
                    }
                }
            })
        }
    </script>



写好后启动服务器,在浏览器上访问html文件测试下,只有输入匹配时,才会跳转到书籍列表页面

在这里插入图片描述

3,图书列表展示

  • 图书列表展示的接口约定:路径为/book/getList,没有请求参数,请求方法为get(从服务器获取数据),响应是返回图书列表,书籍信息如下图:
    在这里插入图片描述



正常开发时,后端是不需要返回statusCN的,直接方法status状态码,前端进行映射,如果为1就是可借阅,如果为其他数就是不可借阅的,这里为了方便一些后续知识的解析,就直接后端返回statusCN(“可借阅”/“不可借阅”)

定义一个书籍类BookInfo,代码如下:
注:double对于0.1和0.01这些十进制小数,在二进制里是无限循环小数,存的时候直接截断,产生误差,因此涉及金钱的属性一般用BigDecimal来定义
再加个Data注解(创建项目已经引入了lombok依赖),如果创建时没有引入,也可以从Maven中央仓库中导入,或者下载个EditStarters插件来引入

package org.example.springbookdemo;

import lombok.Data;

import java.math.BigDecimal;
@Data
public class BookInfo {
    private Integer id;
    private String bookName;
    private String author;
    private Integer count;

    private BigDecimal price;
    private String publish;
    private Integer status;
    private String statusCN;
}



创建一个BookController类,里面写书籍列表展示的后端代码
创建一个List,里面元素的类型是BookInfo,先写个mockBookData方法,模拟下书籍列表,这也是后端开发中常用的一种操作,虽然没有写插入书籍列表的方法,但并不影响测试书籍展示功能
mockBookData方法中,价格设置成0 - 99的随机整数,状态码看i是否能整除5来设置,代码如下:

package org.example.springbookdemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RequestMapping("/book")
@RestController
public class BookController {
    @RequestMapping("/getList")
    public List<BookInfo> getList(){
        List<BookInfo> bookInfos = mockBookData();
        for(BookInfo bookInfo:bookInfos){
            if(bookInfo.getStatus() == 1){
                bookInfo.setStatusCN("可借阅");
            }else{
                bookInfo.setStatusCN("不可借阅");
            }
        }
        return bookInfos;
    }

    public List<BookInfo> mockBookData(){
        List<BookInfo> bookInfos = new ArrayList<>();
        for(int i = 1;i < 8;i++){
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(i);
            bookInfo.setBookName("图书" + i);
            bookInfo.setAuthor("作者" + i);
            bookInfo.setCount(i * 5 + 1);
            bookInfo.setPrice(new BigDecimal(new Random().nextInt(100)));
            bookInfo.setPublish("出版社" + i);
            bookInfo.setStatus(i % 5 == 0 ? 0 : 1);
            bookInfos.add(bookInfo);
        }
        return bookInfos;
    }
}


先启动服务器,在Postman上测试下,就能正确的获得这些数据,如下图:

在这里插入图片描述



接着改下前端的代码,打开booklist.html,前端代码也搞了一些书籍列表的模拟数据,可以参照这些格式在ajax中拼接下,接着把前端中的这些模拟数据删掉即可

在getBookList方法中拼接下书籍列表的每一行(参照前面前端中给的模拟数据,把关键部分替换成book.属性即可),代码如下:

function getBookList() {
                $.ajax({
                    type: "get",
                    url: "/book/getList",
                    success: function (books){
                        let finalHtml = "";
                        for(let book of books){
                            finalHtml += '<tr>'
                            finalHtml += '<td><input type="checkbox" name="selectBook" value= "'+ book.id +'" id="selectBook" class="book-select"></td>'
                            finalHtml += '<td>' + book.id + '</td>'
                            finalHtml += '<td>' + book.bookName + '</td>'
                            finalHtml += '<td>' + book.author + '</td>'
                            finalHtml += '<td>' + book.count + '</td>'
                            finalHtml += '<td>' + book.price + '</td>'
                            finalHtml += '<td>' + book.publish + '</td>'
                            finalHtml += '<td>' + book.statusCN + '</td>'
                            finalHtml += '<td><div class="op">'
                            finalHtml += '<a href="book_update.html?bookId='+ book.id +'">修改</a>'
                            finalHtml += '<a href="javascript:void(0)" onclick="deleteBook('+ book.id +')">删除</a>'
                            finalHtml += '</div></td></tr>'
                        }
                        $("tbody").html(finalHtml)
                    }
                })
            }



完成getBookList方法后,就可以把book_list.html中table的tbody里面的模拟数据都删除掉,删除之后如下图:

在这里插入图片描述



运行程序,在浏览器上访问下book_list.html文件,就能看到后端传输过来的模拟数据了,如下图:

在这里插入图片描述

4,三层架构

项目的功能都是比较多的,如果都是直接创建类,看着还是比较混乱的,如下图:

在这里插入图片描述



如果对类的职责进行划分,不同职责的类放到不同的包中,那代码看起来就比较清晰,后端分为三层架构:

  1. 表现层(controller):接收用户请求,返回列表
  2. 业务逻辑层(service):负责处理业务逻辑,对数据进行加工
  3. 数据访问层(dao):负责存储和管理数据



绝大多数高校数据库都是放在在JavaEE之前的,那时候做的项目就是控制台项目,不涉及客户端和服务器的交互,那时候做项目时的三层架构是这样的:

  • Entity层:实体层,例如项目数据库中有user表,class表
    那就把它们写成user类和class类放到entity层中,user表和class表中的列就对应着类中创建的私有属性
  • Dao层:数据访问层,Dao层中只负责数据的访问,向数据库传入增删改查的SQL指令,Dao层不负责任何逻辑判断(例如不判断插入数据是否合理,逻辑的判断是在service层实现的)
  • Service层:业务逻辑层,负责处理业务逻辑,例如进行逻辑判断(例如校验班名是否重复,进行事务控制,操作多张表等)



因为没有前后端交互,那时候解析的三层架构就不包括表现层,这只是学习阶段的一种叫法,实际的项目肯定是不能只在IDEA控制台上跑的,因此,标准后端开发的三层架构就是表现层(Controller) + 业务逻辑层(Service) + 数据层(Dao)
做项目时仍然会创建Entity包,把实体类放进去,但Entity不算是标准三层架构中的一部分,也就是不作为独立的层级

这里的三层架构和MVC架构都是软件工程领域中的架构模式,MVC架构模式由模型(Model)、视图(View)、控制器(Controller)组成,三层架构将业务应用划分为了表现层、业务逻辑层、数据访问层

如下图,MVC中,视图和控制器合起来对应三层架构中的表现层,模型对应三层架构中的业务逻辑层和数据层,还加上一个实体类

在这里插入图片描述



MVC和三层架构的目的都是为了实现“解耦、分层、代码复用”,从不同角度对软件工程进行了抽象

  • MVC强调数据和视图分离,将数据展示和数据处理分开,通过控制器对两者进行组合
  • 三层架构强调不同维度数据处理的高内聚和低耦合,将交互界面、业务处理和数据库操作逻辑分开



前面的代码写的是比较混乱的,就比如BookController类,同时完成了表现层(接收前端传来的请求)、业务逻辑层(判断图书是否可以借阅)、数据访问层(拿到书籍列表)的功能

接下来就按照三层架构来写下代码,创建四个包:entity(放实体类)、service(业务逻辑层)、controller(表现层)、dao(数据访问层)

首先把bookInfo放到实体类中,这里只对BookController(图书列表展示)进行一个拆分,登录功能因为还没有调数据库,而且也比较简单,就没必要进行拆分了
BookController中创建BookService对象,拿到bookInfos,返回给客户端

package org.example.springbookdemo.controller;

import org.example.springbookdemo.entity.BookInfo;
import org.example.springbookdemo.service.BookService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;

@RequestMapping("/book")
@RestController
public class BookController {
    @RequestMapping("/getList")
    public List<BookInfo> getList(){
        BookService bookService = new BookService();
        List<BookInfo> bookInfos = bookService.getList();
        return bookInfos;
    }
}



BookService中创建BookDao对象,拿到bookInfos,处理下业务逻辑(判断图书是否可借阅)

package org.example.springbookdemo.service;

import org.example.springbookdemo.dao.BookDao;
import org.example.springbookdemo.entity.BookInfo;

import java.util.List;

public class BookService {
    public List<BookInfo> getList(){
        BookDao bookDao = new BookDao();
        List<BookInfo> bookInfos = bookDao.mockBookData();
        for(BookInfo bookInfo:bookInfos){
            if(bookInfo.getStatus() == 1){
                bookInfo.setStatusCN("可借阅");
            }else{
                bookInfo.setStatusCN("不可借阅");
            }
        }
        return bookInfos;
    }
}



BookDao就是直接拿到原始数据,返回给BookService

package org.example.springbookdemo.dao;

import org.example.springbookdemo.entity.BookInfo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class BookDao {
    public List<BookInfo> mockBookData(){
        List<BookInfo> bookInfos = new ArrayList<>();
        for(int i = 1;i < 8;i++){
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(i);
            bookInfo.setBookName("图书" + i);
            bookInfo.setAuthor("作者" + i);
            bookInfo.setCount(i * 5 + 1);
            bookInfo.setPrice(new BigDecimal(new Random().nextInt(100)));
            bookInfo.setPublish("出版社" + i);
            bookInfo.setStatus(i % 5 == 0 ? 0 : 1);
            bookInfos.add(bookInfo);
        }
        return bookInfos;
    }
}

在这里插入图片描述

结语

  • 分析出需求后,代码的处理逻辑并不算复杂,主要是使用三层架构,把逻辑进行拆分,每一层负责各自功能
  • 建议铁汁们把前端代码拷贝到项目中,自己从头到尾写下代码,如果有报错的话先看日志,分析是前端出错还是后端出错,并对错误进行定位,完整的代码博主放在了Spring-book-demo中,有需要的铁汁可以使用

在这里插入图片描述



以上就是今天的所有内容啦~完结撒花~🥳🎉🎉

在这里插入图片描述

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值