Repository: xqnode/library-management Branch: main Commit: 67336e354ce4 Files: 90 Total size: 192.8 KB Directory structure: gitextract_baa2hq15/ ├── .gitignore ├── LICENSE ├── README.md ├── springboot/ │ ├── pom.xml │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── example/ │ │ │ └── springboot/ │ │ │ ├── SpringbootApplication.java │ │ │ ├── common/ │ │ │ │ ├── CorsConfig.java │ │ │ │ ├── JwtInterceptor.java │ │ │ │ ├── Result.java │ │ │ │ └── WebConfig.java │ │ │ ├── controller/ │ │ │ │ ├── AdminController.java │ │ │ │ ├── BookController.java │ │ │ │ ├── BorrowController.java │ │ │ │ ├── CategoryController.java │ │ │ │ ├── UserController.java │ │ │ │ ├── dto/ │ │ │ │ │ └── LoginDTO.java │ │ │ │ └── request/ │ │ │ │ ├── AdminPageRequest.java │ │ │ │ ├── BaseRequest.java │ │ │ │ ├── BookPageRequest.java │ │ │ │ ├── BorrowPageRequest.java │ │ │ │ ├── CategoryPageRequest.java │ │ │ │ ├── LoginRequest.java │ │ │ │ ├── PasswordRequest.java │ │ │ │ └── UserPageRequest.java │ │ │ ├── entity/ │ │ │ │ ├── Admin.java │ │ │ │ ├── BaseEntity.java │ │ │ │ ├── Book.java │ │ │ │ ├── Borrow.java │ │ │ │ ├── Category.java │ │ │ │ ├── Retur.java │ │ │ │ └── User.java │ │ │ ├── exception/ │ │ │ │ ├── ExceptionHandle.java │ │ │ │ └── ServiceException.java │ │ │ ├── mapper/ │ │ │ │ ├── AdminMapper.java │ │ │ │ ├── BookMapper.java │ │ │ │ ├── BorrowMapper.java │ │ │ │ ├── CategoryMapper.java │ │ │ │ ├── UserMapper.java │ │ │ │ └── po/ │ │ │ │ └── BorrowReturCountPO.java │ │ │ ├── service/ │ │ │ │ ├── IAdminService.java │ │ │ │ ├── IBookService.java │ │ │ │ ├── IBorrowService.java │ │ │ │ ├── ICategoryService.java │ │ │ │ ├── IUserService.java │ │ │ │ └── impl/ │ │ │ │ ├── AdminService.java │ │ │ │ ├── BookService.java │ │ │ │ ├── BorrowService.java │ │ │ │ ├── CategoryService.java │ │ │ │ └── UserService.java │ │ │ └── utils/ │ │ │ └── TokenUtils.java │ │ └── resources/ │ │ ├── application.yml │ │ └── mapper/ │ │ ├── Admin.xml │ │ ├── Book.xml │ │ ├── Borrow.xml │ │ ├── Category.xml │ │ └── User.xml │ └── test/ │ └── java/ │ └── com/ │ └── example/ │ └── springboot/ │ └── SpringbootApplicationTests.java ├── sql/ │ └── library-management.sql ├── vue/ │ ├── README.md │ ├── babel.config.js │ ├── jsconfig.json │ ├── package.json │ ├── public/ │ │ └── index.html │ ├── src/ │ │ ├── App.vue │ │ ├── assets/ │ │ │ └── global.css │ │ ├── main.js │ │ ├── router/ │ │ │ └── index.js │ │ ├── utils/ │ │ │ └── request.js │ │ └── views/ │ │ ├── 404.vue │ │ ├── Layout.vue │ │ ├── admin/ │ │ │ ├── Add.vue │ │ │ ├── Edit.vue │ │ │ └── List.vue │ │ ├── book/ │ │ │ ├── Add.vue │ │ │ ├── Edit.vue │ │ │ └── List.vue │ │ ├── borrow/ │ │ │ ├── Add.vue │ │ │ ├── Edit.vue │ │ │ └── List.vue │ │ ├── category/ │ │ │ ├── Add.vue │ │ │ ├── Edit.vue │ │ │ └── List.vue │ │ ├── home/ │ │ │ └── HomeView.vue │ │ ├── login/ │ │ │ └── Login.vue │ │ ├── retur/ │ │ │ └── List.vue │ │ └── user/ │ │ ├── AddUser.vue │ │ ├── EditUser.vue │ │ └── User.vue │ └── vue.config.js └── 文档/ ├── 笔记.md └── 首页Echarts.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules dist target # Editor directories and files .idea .vscode *.iml ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ # 从0开始做前后端分离的图书管理系统 技术栈:SpringBoot2 + Vue2.0 + ElementUI + Mysql 免费开源,完全手写,适合小白,求求 Star [课程笔记点这里](文档/笔记.md) 关注B站:[程序员青戈](https://space.bilibili.com/402779077) ,学习更多干货教程 关注微信公众号:Java学习指南,回复:软件,获取课程所需的所有软件下载和安装教程。 ## 系统登录 http://localhost:8080/login 账号:admin/admin ## 系统功能 ## 系统截图 ## 老铁,白嫖完了,真的别忘了 Star 噢! ================================================ FILE: springboot/pom.xml ================================================ 4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.3 com.example springboot 0.0.1-SNAPSHOT springboot Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.2 mysql mysql-connector-java runtime org.projectlombok lombok true com.github.pagehelper pagehelper-spring-boot-starter 1.4.5 cn.hutool hutool-all 5.8.0 com.auth0 java-jwt 3.10.3 org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok ================================================ FILE: springboot/src/main/java/com/example/springboot/SpringbootApplication.java ================================================ package com.example.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } // 健康检查的接口 @GetMapping public String health() { return "SUCCESS"; } } ================================================ FILE: springboot/src/main/java/com/example/springboot/common/CorsConfig.java ================================================ package com.example.springboot.common; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置 return new CorsFilter(source); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/common/JwtInterceptor.java ================================================ package com.example.springboot.common; import cn.hutool.core.util.StrUtil; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.example.springboot.entity.Admin; import com.example.springboot.exception.ServiceException; import com.example.springboot.service.IAdminService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component @Slf4j public class JwtInterceptor implements HandlerInterceptor { private static final String ERROR_CODE_401 = "401"; @Autowired private IAdminService adminService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { String token = request.getHeader("token"); if (StrUtil.isBlank(token)) { token = request.getParameter("token"); } // 执行认证 if (StrUtil.isBlank(token)) { throw new ServiceException(ERROR_CODE_401, "无token,请重新登录"); } // 获取 token 中的adminId String adminId; Admin admin; try { adminId = JWT.decode(token).getAudience().get(0); // 根据token中的userid查询数据库 admin = adminService.getById(Integer.parseInt(adminId)); } catch (Exception e) { String errMsg = "token验证失败,请重新登录"; log.error(errMsg + ", token=" + token, e); throw new ServiceException(ERROR_CODE_401, errMsg); } if (admin == null) { throw new ServiceException(ERROR_CODE_401, "用户不存在,请重新登录"); } try { // 用户密码加签验证 token JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build(); jwtVerifier.verify(token); // 验证token } catch (JWTVerificationException e) { throw new ServiceException(ERROR_CODE_401, "token验证失败,请重新登录"); } return true; } } ================================================ FILE: springboot/src/main/java/com/example/springboot/common/Result.java ================================================ package com.example.springboot.common; import lombok.Data; @Data public class Result { private static final String SUCCESS_CODE = "200"; private static final String ERROR_CODE = "-1"; private String code; private Object data; private String msg; public static Result success() { Result result = new Result(); result.setCode(SUCCESS_CODE); return result; } public static Result success(Object data) { Result result = new Result(); result.setCode(SUCCESS_CODE); result.setData(data); return result; } public static Result error(String msg) { Result result = new Result(); result.setCode(ERROR_CODE); result.setMsg(msg); return result; } public static Result error(String code, String msg) { Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } } ================================================ FILE: springboot/src/main/java/com/example/springboot/common/WebConfig.java ================================================ package com.example.springboot.common; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired JwtInterceptor jwtInterceptor; @Override public void configurePathMatch(PathMatchConfigurer configurer) { // 指定controller统一的接口前缀 configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(RestController.class)); } // 加自定义拦截器JwtInterceptor,设置拦截规则 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**").excludePathPatterns("/api/admin/login"); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/AdminController.java ================================================ package com.example.springboot.controller; import com.example.springboot.common.Result; import com.example.springboot.controller.dto.LoginDTO; import com.example.springboot.controller.request.AdminPageRequest; import com.example.springboot.controller.request.LoginRequest; import com.example.springboot.controller.request.PasswordRequest; import com.example.springboot.entity.Admin; import com.example.springboot.service.IAdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin @RestController @RequestMapping("/admin") public class AdminController { @Autowired IAdminService adminService; @PostMapping("/login") public Result login(@RequestBody LoginRequest request) { LoginDTO login = adminService.login(request); return Result.success(login); } @PutMapping("/password") public Result password(@RequestBody PasswordRequest request) { adminService.changePass(request); return Result.success(); } @PostMapping("/save") public Result save(@RequestBody Admin obj) { adminService.save(obj); return Result.success(); } @PutMapping("/update") public Result update(@RequestBody Admin obj) { adminService.update(obj); return Result.success(); } @DeleteMapping("/delete/{id}") public Result delete(@PathVariable Integer id) { adminService.deleteById(id); return Result.success(); } @GetMapping("/{id}") public Result getById(@PathVariable Integer id) { Admin obj = adminService.getById(id); return Result.success(obj); } @GetMapping("/list") public Result list() { List list = adminService.list(); return Result.success(list); } @GetMapping("/page") public Result page(AdminPageRequest pageRequest) { return Result.success(adminService.page(pageRequest)); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/BookController.java ================================================ package com.example.springboot.controller; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import com.example.springboot.common.Result; import com.example.springboot.controller.request.BookPageRequest; import com.example.springboot.entity.Admin; import com.example.springboot.entity.Book; import com.example.springboot.service.IBookService; import com.example.springboot.utils.TokenUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; @Slf4j @CrossOrigin @RestController @RequestMapping("/book") public class BookController { @Autowired IBookService bookService; private static final String BASE_FILE_PATH = System.getProperty("user.dir") + "/files/"; @PostMapping("/file/upload") public Result uploadFile(MultipartFile file) { String originalFilename = file.getOriginalFilename(); if (StrUtil.isBlank(originalFilename)) { return Result.error("文件上传失败"); } long flag = System.currentTimeMillis(); String filePath = BASE_FILE_PATH + flag + "_" + originalFilename; try { FileUtil.mkParentDirs(filePath); // 创建父级目录 file.transferTo(FileUtil.file(filePath)); Admin currentAdmin = TokenUtils.getCurrentAdmin(); String token = TokenUtils.genToken(currentAdmin.getId().toString(), currentAdmin.getPassword(), 15); String url = "http://localhost:9090/api/book/file/download/" + flag + "?&token=" + token; if (originalFilename.endsWith("png") || originalFilename.endsWith("jpg") || originalFilename.endsWith("pdf")) { url += "&play=1"; } return Result.success(url); } catch (Exception e) { log.info("文件上传失败", e); } return Result.error("文件上传失败"); } @GetMapping("/file/download/{flag}") public void download(@PathVariable String flag, @RequestParam(required = false) String play, HttpServletResponse response) { OutputStream os; List fileNames = FileUtil.listFileNames(BASE_FILE_PATH); String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse(""); // System.currentTimeMillis() + originalFilename try { if (StrUtil.isNotEmpty(fileName)) { String realName = fileName.substring(fileName.indexOf("_") + 1); if ("1".equals(play)) { response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(realName, "UTF-8")); } else { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realName, "UTF-8")); } byte[] bytes = FileUtil.readBytes(BASE_FILE_PATH + fileName); os = response.getOutputStream(); os.write(bytes); os.flush(); os.close(); } } catch (Exception e) { log.error("文件下载失败", e); } } @PostMapping("/save") public Result save(@RequestBody Book obj) { bookService.save(obj); return Result.success(); } @PutMapping("/update") public Result update(@RequestBody Book obj) { bookService.update(obj); return Result.success(); } @DeleteMapping("/delete/{id}") public Result delete(@PathVariable Integer id) { bookService.deleteById(id); return Result.success(); } @GetMapping("/{id}") public Result getById(@PathVariable Integer id) { Book obj = bookService.getById(id); return Result.success(obj); } @GetMapping("/list") public Result list() { List list = bookService.list(); return Result.success(list); } @GetMapping("/page") public Result page(BookPageRequest pageRequest) { return Result.success(bookService.page(pageRequest)); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/BorrowController.java ================================================ package com.example.springboot.controller; import com.example.springboot.common.Result; import com.example.springboot.controller.request.BorrowPageRequest; import com.example.springboot.entity.Borrow; import com.example.springboot.entity.Retur; import com.example.springboot.service.IBorrowService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin @RestController @RequestMapping("/borrow") public class BorrowController { @Autowired IBorrowService borrowService; @PostMapping("/save") public Result save(@RequestBody Borrow obj) { borrowService.save(obj); return Result.success(); } @PutMapping("/update") public Result update(@RequestBody Borrow obj) { borrowService.update(obj); return Result.success(); } @DeleteMapping("/delete/{id}") public Result delete(@PathVariable Integer id) { borrowService.deleteById(id); return Result.success(); } @GetMapping("/{id}") public Result getById(@PathVariable Integer id) { Borrow obj = borrowService.getById(id); return Result.success(obj); } @GetMapping("/list") public Result list() { List list = borrowService.list(); return Result.success(list); } @GetMapping("/page") public Result page(BorrowPageRequest pageRequest) { return Result.success(borrowService.page(pageRequest)); } @GetMapping("/pageRetur") public Result pageRetur(BorrowPageRequest pageRequest) { return Result.success(borrowService.pageRetur(pageRequest)); } @PostMapping("/saveRetur") public Result saveRetur(@RequestBody Retur obj) { borrowService.saveRetur(obj); return Result.success(); } @DeleteMapping("/deleteRetur/{id}") public Result deleteRetur(@PathVariable Integer id) { borrowService.deleteReturById(id); return Result.success(); } @GetMapping("/lineCharts/{timeRange}") public Result lineCharts(@PathVariable String timeRange) { return Result.success(borrowService.getCountByTimeRange(timeRange)); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/CategoryController.java ================================================ package com.example.springboot.controller; import cn.hutool.core.collection.CollUtil; import com.example.springboot.common.Result; import com.example.springboot.controller.request.AdminPageRequest; import com.example.springboot.controller.request.CategoryPageRequest; import com.example.springboot.entity.Book; import com.example.springboot.entity.Category; import com.example.springboot.service.ICategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @CrossOrigin @RestController @RequestMapping("/category") public class CategoryController { @Autowired ICategoryService categoryService; @PostMapping("/save") public Result save(@RequestBody Category obj) { categoryService.save(obj); return Result.success(); } @PutMapping("/update") public Result update(@RequestBody Category obj) { categoryService.update(obj); return Result.success(); } @DeleteMapping("/delete/{id}") public Result delete(@PathVariable Integer id) { categoryService.deleteById(id); return Result.success(); } @GetMapping("/{id}") public Result getById(@PathVariable Integer id) { Category obj = categoryService.getById(id); return Result.success(obj); } @GetMapping("/list") public Result list() { List list = categoryService.list(); return Result.success(list); } @GetMapping("/tree") public Result tree() { List list = categoryService.list(); // 对list操作即可 // List treeList = list.stream().filter(v -> v.getPid() == null).collect(Collectors.toList()); // 第一层 // 比如 递归实现 children列表的查询 return Result.success(createTree(null, list)); // null 表示从第一级开始递归 } // 完全递归的方法来实现递归树 private List createTree(Integer pid, List categories) { List treeList = new ArrayList<>(); for (Category category : categories) { if (pid == null) { if (category.getPid() == null) { // 那这就是第一级节点 treeList.add(category); category.setChildren(createTree(category.getId(), categories)); } } else { if (pid.equals(category.getPid())) { treeList.add(category); category.setChildren(createTree(category.getId(), categories)); } } if (CollUtil.isEmpty(category.getChildren())) { category.setChildren(null); } } return treeList; } @GetMapping("/page") public Result page(CategoryPageRequest pageRequest) { return Result.success(categoryService.page(pageRequest)); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/UserController.java ================================================ package com.example.springboot.controller; import com.example.springboot.common.Result; import com.example.springboot.controller.request.UserPageRequest; import com.example.springboot.entity.User; import com.example.springboot.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin @RestController @RequestMapping("/user") public class UserController { @Autowired IUserService userService; @PostMapping("/save") public Result save(@RequestBody User user) { userService.save(user); return Result.success(); } @PostMapping("/account") public Result account(@RequestBody User user) { userService.handleAccount(user); return Result.success(); } @PutMapping("/update") public Result update(@RequestBody User user) { userService.update(user); return Result.success(); } @DeleteMapping("/delete/{id}") public Result delete(@PathVariable Integer id) { userService.deleteById(id); return Result.success(); } @GetMapping("/{id}") public Result getById(@PathVariable Integer id) { User user = userService.getById(id); return Result.success(user); } @GetMapping("/list") public Result list() { List users = userService.list(); return Result.success(users); } @GetMapping("/page") public Result page(UserPageRequest userPageRequest) { return Result.success(userService.page(userPageRequest)); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/dto/LoginDTO.java ================================================ package com.example.springboot.controller.dto; import lombok.Data; @Data public class LoginDTO { private Integer id; private String username; private String phone; private String email; private String token; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/AdminPageRequest.java ================================================ package com.example.springboot.controller.request; import lombok.Data; @Data public class AdminPageRequest extends BaseRequest{ private String username; private String phone; private String email; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/BaseRequest.java ================================================ package com.example.springboot.controller.request; import lombok.Data; @Data public class BaseRequest { private Integer pageNum = 1; private Integer pageSize = 10; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/BookPageRequest.java ================================================ package com.example.springboot.controller.request; import lombok.Data; @Data public class BookPageRequest extends BaseRequest{ private String name; private String bookNo; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/BorrowPageRequest.java ================================================ package com.example.springboot.controller.request; import lombok.Data; @Data public class BorrowPageRequest extends BaseRequest{ private String bookName; private String bookNo; private String userName; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/CategoryPageRequest.java ================================================ package com.example.springboot.controller.request; import lombok.Data; @Data public class CategoryPageRequest extends BaseRequest{ private String name; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/LoginRequest.java ================================================ package com.example.springboot.controller.request; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data public class LoginRequest { private String username; private String password; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/PasswordRequest.java ================================================ package com.example.springboot.controller.request; import lombok.Data; @Data public class PasswordRequest { private String username; private String password; private String newPass; } ================================================ FILE: springboot/src/main/java/com/example/springboot/controller/request/UserPageRequest.java ================================================ package com.example.springboot.controller.request; import lombok.Data; @Data public class UserPageRequest extends BaseRequest{ private String name; private String phone; } ================================================ FILE: springboot/src/main/java/com/example/springboot/entity/Admin.java ================================================ package com.example.springboot.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; @Data public class Admin { private Integer id; private String username; private String phone; private String email; private String password; @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private Date createtime; @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private Date updatetime; private boolean status; } ================================================ FILE: springboot/src/main/java/com/example/springboot/entity/BaseEntity.java ================================================ package com.example.springboot.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.io.Serializable; import java.time.LocalDate; @Data public class BaseEntity implements Serializable { private static final long serialVersionUID = 1L; private Integer id; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate createtime; /** * 更新时间 */ @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate updatetime; } ================================================ FILE: springboot/src/main/java/com/example/springboot/entity/Book.java ================================================ package com.example.springboot.entity; import lombok.Data; import java.io.Serializable; import java.util.List; @Data public class Book extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 名称 */ private String name; /** * 描述 */ private String description; /** * 出版日期 */ private String publishDate; /** * 作者 */ private String author; /** * 出版社 */ private String publisher; /** * 分类 */ private String category; /** * 标准码 */ private String bookNo; /** * 封面 */ private String cover; private List categories; private Integer score; private Integer nums; } ================================================ FILE: springboot/src/main/java/com/example/springboot/entity/Borrow.java ================================================ package com.example.springboot.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.time.LocalDate; @Data public class Borrow { /** * id */ private Integer id; /** * 图书名称 */ private String bookName; /** * 图书标准码 */ private String bookNo; /** * 用户id */ private String userNo; /** * 用户名称 */ private String userName; /** * 用户联系方式 */ private String userPhone; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate createtime; /** * 更新时间 */ @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate updatetime; /** * 借书积分 */ private Integer score; private String status; private Integer days; private LocalDate returnDate; // 提醒状态 即将到期(-1) 已到期(当天) 已过期(超过归还日期之后) private String note; } ================================================ FILE: springboot/src/main/java/com/example/springboot/entity/Category.java ================================================ package com.example.springboot.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.time.LocalDate; import java.util.List; @Data public class Category { private Integer id; private String name; private String remark; private Integer pid; @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate createtime; @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate updatetime; private List children; } ================================================ FILE: springboot/src/main/java/com/example/springboot/entity/Retur.java ================================================ package com.example.springboot.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.time.LocalDate; @Data public class Retur { /** * id */ private Integer id; /** * 图书名称 */ private String bookName; /** * 图书标准码 */ private String bookNo; /** * 用户id */ private String userNo; /** * 用户名称 */ private String userName; /** * 用户联系方式 */ private String userPhone; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate createtime; /** * 更新时间 */ @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate updatetime; /** * 借书积分 */ private Integer score; private String status; private Integer days; private LocalDate returnDate; private LocalDate realDate; } ================================================ FILE: springboot/src/main/java/com/example/springboot/entity/User.java ================================================ package com.example.springboot.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.beans.Transient; import java.util.Date; @Data public class User { private Integer id; private String name; private String username; private Integer age; private Integer account; private Integer score; private String sex; private String phone; private String address; @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private Date createtime; @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private Date updatetime; private boolean status; } ================================================ FILE: springboot/src/main/java/com/example/springboot/exception/ExceptionHandle.java ================================================ package com.example.springboot.exception; import cn.hutool.core.util.StrUtil; import com.example.springboot.common.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @Slf4j @RestControllerAdvice public class ExceptionHandle { @ExceptionHandler(value = ServiceException.class) public Result serviceExceptionError(ServiceException e) { log.error("业务异常", e); String code = e.getCode(); if (StrUtil.isNotBlank(code)) { return Result.error(code, e.getMessage()); } return Result.error(e.getMessage()); } @ExceptionHandler(value = Exception.class) public Result exceptionError(Exception e) { log.error("系统错误", e); return Result.error("系统错误"); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/exception/ServiceException.java ================================================ package com.example.springboot.exception; public class ServiceException extends RuntimeException{ private String code; public String getCode() { return code; } public ServiceException(String message, Throwable cause) { super(message, cause); } public ServiceException(String message) { super(message); } public ServiceException(String code, String message) { super(message); this.code = code; } } ================================================ FILE: springboot/src/main/java/com/example/springboot/mapper/AdminMapper.java ================================================ package com.example.springboot.mapper; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.controller.request.LoginRequest; import com.example.springboot.controller.request.PasswordRequest; import com.example.springboot.entity.Admin; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface AdminMapper { List list(); List listByCondition(BaseRequest baseRequest); void save(Admin obj); Admin getById(Integer id); void updateById(Admin user); void deleteById(Integer id); Admin getByUsernameAndPassword(@Param("username") String username, @Param("password") String password); int updatePassword(PasswordRequest request); Admin getByUsername(String username); } ================================================ FILE: springboot/src/main/java/com/example/springboot/mapper/BookMapper.java ================================================ package com.example.springboot.mapper; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Book; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface BookMapper { List list(); List listByCondition(BaseRequest baseRequest); void save(Book obj); Book getById(Integer id); void updateById(Book user); void deleteById(Integer id); Book getByNo(String bookNo); void updateNumByNo(String bookNo); } ================================================ FILE: springboot/src/main/java/com/example/springboot/mapper/BorrowMapper.java ================================================ package com.example.springboot.mapper; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Borrow; import com.example.springboot.entity.Retur; import com.example.springboot.mapper.po.BorrowReturCountPO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface BorrowMapper { List list(); List listByCondition(BaseRequest baseRequest); List listReturByCondition(BaseRequest baseRequest); void save(Borrow obj); void saveRetur(Retur obj); Borrow getById(Integer id); void updateById(Borrow user); void deleteById(Integer id); void deleteReturById(Integer id); void updateStatus(String status, Integer id); List getCountByTimeRange(@Param("timeRange") String timeRange, @Param("type") int type); // 1 borrow 2 return } ================================================ FILE: springboot/src/main/java/com/example/springboot/mapper/CategoryMapper.java ================================================ package com.example.springboot.mapper; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.controller.request.PasswordRequest; import com.example.springboot.entity.Admin; import com.example.springboot.entity.Category; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface CategoryMapper { List list(); List listByCondition(BaseRequest baseRequest); void save(Category obj); Category getById(Integer id); void updateById(Category user); void deleteById(Integer id); } ================================================ FILE: springboot/src/main/java/com/example/springboot/mapper/UserMapper.java ================================================ package com.example.springboot.mapper; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface UserMapper { // @Select("select * from user") List list(); List listByCondition(BaseRequest baseRequest); void save(User user); User getById(Integer id); void updateById(User user); void deleteById(Integer id); User getByUsername(String username); } ================================================ FILE: springboot/src/main/java/com/example/springboot/mapper/po/BorrowReturCountPO.java ================================================ package com.example.springboot.mapper.po; import lombok.Data; @Data public class BorrowReturCountPO { private String date; private Integer count; } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/IAdminService.java ================================================ package com.example.springboot.service; import com.example.springboot.controller.dto.LoginDTO; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.controller.request.LoginRequest; import com.example.springboot.controller.request.PasswordRequest; import com.example.springboot.entity.Admin; import com.github.pagehelper.PageInfo; import java.util.List; public interface IAdminService { List list(); PageInfo page(BaseRequest baseRequest); void save(Admin obj); Admin getById(Integer id); void update(Admin obj); void deleteById(Integer id); LoginDTO login(LoginRequest request); void changePass(PasswordRequest request); } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/IBookService.java ================================================ package com.example.springboot.service; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Book; import com.github.pagehelper.PageInfo; import java.util.List; public interface IBookService { List list(); PageInfo page(BaseRequest baseRequest); void save(Book obj); Book getById(Integer id); void update(Book obj); void deleteById(Integer id); } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/IBorrowService.java ================================================ package com.example.springboot.service; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Borrow; import com.example.springboot.entity.Retur; import com.github.pagehelper.PageInfo; import java.util.List; import java.util.Map; public interface IBorrowService { List list(); PageInfo page(BaseRequest baseRequest); void save(Borrow obj); PageInfo pageRetur(BaseRequest baseRequest); void saveRetur(Retur obj); Borrow getById(Integer id); void update(Borrow obj); void deleteById(Integer id); void deleteReturById(Integer id); Map getCountByTimeRange(String timeRange); } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/ICategoryService.java ================================================ package com.example.springboot.service; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Category; import com.github.pagehelper.PageInfo; import java.util.List; public interface ICategoryService { List list(); PageInfo page(BaseRequest baseRequest); void save(Category obj); Category getById(Integer id); void update(Category obj); void deleteById(Integer id); } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/IUserService.java ================================================ package com.example.springboot.service; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.controller.request.UserPageRequest; import com.example.springboot.entity.User; import com.github.pagehelper.PageInfo; import java.util.List; public interface IUserService { List list(); PageInfo page(BaseRequest baseRequest); void save(User user); User getById(Integer id); void update(User user); void deleteById(Integer id); void handleAccount(User user); } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/impl/AdminService.java ================================================ package com.example.springboot.service.impl; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.SecureUtil; import com.example.springboot.controller.dto.LoginDTO; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.controller.request.LoginRequest; import com.example.springboot.controller.request.PasswordRequest; import com.example.springboot.entity.Admin; import com.example.springboot.exception.ServiceException; import com.example.springboot.mapper.AdminMapper; import com.example.springboot.service.IAdminService; import com.example.springboot.utils.TokenUtils; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; @Slf4j @Service public class AdminService implements IAdminService { @Autowired AdminMapper adminMapper; private static final String DEFAULT_PASS = "123"; private static final String PASS_SALT = "qingge"; @Override public List list() { return adminMapper.list(); } @Override public PageInfo page(BaseRequest baseRequest) { PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize()); List users = adminMapper.listByCondition(baseRequest); return new PageInfo<>(users); } @Override public void save(Admin obj) { // 默认密码 123 if (StrUtil.isBlank(obj.getPassword())) { obj.setPassword(DEFAULT_PASS); } obj.setPassword(securePass(obj.getPassword())); // 设置md5加密,加盐 try { adminMapper.save(obj); } catch (DuplicateKeyException e) { log.error("数据插入失败, username:{}", obj.getUsername(), e); throw new ServiceException("用户名重复"); } } @Override public Admin getById(Integer id) { return adminMapper.getById(id); } @Override public void update(Admin user) { user.setUpdatetime(new Date()); adminMapper.updateById(user); } @Override public void deleteById(Integer id) { adminMapper.deleteById(id); } @Override public LoginDTO login(LoginRequest request) { Admin admin = null; try { admin = adminMapper.getByUsername(request.getUsername()); } catch (Exception e) { log.error("根据用户名{} 查询出错", request.getUsername()); throw new ServiceException("用户名错误"); } if (admin == null) { throw new ServiceException("用户名或密码错误"); } // 判断密码是否合法 String securePass = securePass(request.getPassword()); if (!securePass.equals(admin.getPassword())) { throw new ServiceException("用户名或密码错误"); } if (!admin.isStatus()) { throw new ServiceException("当前用户处于禁用状态,请联系管理员"); } LoginDTO loginDTO = new LoginDTO(); BeanUtils.copyProperties(admin, loginDTO); // 生成token String token = TokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassword()); loginDTO.setToken(token); return loginDTO; } @Override public void changePass(PasswordRequest request) { // 注意 你要对新的密码进行加密 request.setNewPass(securePass(request.getNewPass())); int count = adminMapper.updatePassword(request); if (count <= 0) { throw new ServiceException("修改密码失败"); } } private String securePass(String password) { return SecureUtil.md5(password + PASS_SALT); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/impl/BookService.java ================================================ package com.example.springboot.service.impl; import cn.hutool.core.collection.CollUtil; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Book; import com.example.springboot.exception.ServiceException; import com.example.springboot.mapper.BookMapper; import com.example.springboot.service.IBookService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.time.LocalDate; import java.util.List; @Service @Slf4j public class BookService implements IBookService { @Resource BookMapper bookMapper; @Override public List list() { return bookMapper.list(); } @Override public PageInfo page(BaseRequest baseRequest) { PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize()); return new PageInfo<>(bookMapper.listByCondition(baseRequest)); } @Override public void save(Book obj) { try { obj.setCategory(category(obj.getCategories())); bookMapper.save(obj); } catch (Exception e) { throw new ServiceException("数据插入错误", e); } } @Override public Book getById(Integer id) { return bookMapper.getById(id); } @Override public void update(Book obj) { try { obj.setCategory(category(obj.getCategories())); obj.setUpdatetime(LocalDate.now()); bookMapper.updateById(obj); } catch (Exception e) { throw new ServiceException("数据更新错误", e); } } @Override public void deleteById(Integer id) { bookMapper.deleteById(id); } private String category(List categories) { StringBuilder sb = new StringBuilder(); if (CollUtil.isNotEmpty(categories)) { categories.forEach(v -> sb.append(v).append(" > ")); return sb.substring(0, sb.lastIndexOf(" > ")); } return sb.toString(); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/impl/BorrowService.java ================================================ package com.example.springboot.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Book; import com.example.springboot.entity.Borrow; import com.example.springboot.entity.Retur; import com.example.springboot.entity.User; import com.example.springboot.exception.ServiceException; import com.example.springboot.mapper.BookMapper; import com.example.springboot.mapper.BorrowMapper; import com.example.springboot.mapper.UserMapper; import com.example.springboot.mapper.po.BorrowReturCountPO; import com.example.springboot.service.IBorrowService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.*; @Service @Slf4j public class BorrowService implements IBorrowService { @Resource BorrowMapper borrowMapper; @Autowired UserMapper userMapper; @Autowired BookMapper bookMapper; @Override public List list() { return borrowMapper.list(); } @Override public PageInfo page(BaseRequest baseRequest) { PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize()); List borrows = borrowMapper.listByCondition(baseRequest); for (Borrow borrow : borrows) { LocalDate returnDate = borrow.getReturnDate(); LocalDate now = LocalDate.now(); if (now.plusDays(1).isEqual(returnDate)) { // 当前日期比归还的日期小一天 borrow.setNote("即将到期"); } else if (now.isEqual(returnDate)) { borrow.setNote("已到期"); } else if (now.isAfter(returnDate)) { borrow.setNote("已过期"); } else { borrow.setNote("正常"); } } return new PageInfo<>(borrows); } @Override @Transactional public void save(Borrow obj) { // 1. 校验用户的积分是否足够 String userNo = obj.getUserNo(); User user = userMapper.getByUsername(userNo); if (Objects.isNull(user)) { throw new ServiceException("用户不存在"); } // 2. 校验图书的数量是否足够 Book book = bookMapper.getByNo(obj.getBookNo()); if (Objects.isNull(book)) { throw new ServiceException("所借图书不存在"); } // 3. 校验图书数量 if (book.getNums() < 1) { throw new ServiceException("图书数量不足"); } Integer account = user.getAccount(); Integer score = book.getScore() * obj.getDays(); // score = 借1本的积分 * 天数 // 4. 校验用户账户余额 if (score > account) { throw new ServiceException("用户积分不足"); } // 5. 更新用户余额 user.setAccount(user.getAccount() - score); userMapper.updateById(user); // 6. 更新图书的数量 book.setNums(book.getNums() - 1); bookMapper.updateById(book); obj.setReturnDate(LocalDate.now().plus(obj.getDays(), ChronoUnit.DAYS)); // 当前的日期加 days 得到归还的日期 obj.setScore(score); // 7. 新增借书记录 borrowMapper.save(obj); } @Override public PageInfo pageRetur(BaseRequest baseRequest) { PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize()); return new PageInfo<>(borrowMapper.listReturByCondition(baseRequest)); } // 还书逻辑 @Transactional @Override public void saveRetur(Retur obj) { // 改状态 obj.setStatus("已归还"); borrowMapper.updateStatus("已归还", obj.getId()); // obj.getId() 是前端传来的借书id // obj.setId(null); // 新数据 obj.setRealDate(LocalDate.now()); borrowMapper.saveRetur(obj); // 图书数量增加 bookMapper.updateNumByNo(obj.getBookNo()); // 返还和扣除用户积分 Book book = bookMapper.getByNo(obj.getBookNo()); if (book != null) { long until = 0; if (obj.getRealDate().isBefore(obj.getReturnDate())) { until = obj.getRealDate().until(obj.getReturnDate(), ChronoUnit.DAYS); } else if (obj.getRealDate().isAfter(obj.getReturnDate())) { // 逾期归还,要扣额外的积分 until = -obj.getReturnDate().until(obj.getRealDate(), ChronoUnit.DAYS); } int score = (int) until * book.getScore(); // 获取待归还的积分 User user = userMapper.getByUsername(obj.getUserNo()); int account = user.getAccount() + score; user.setAccount(account); if (account < 0) { // 锁定账号 user.setStatus(false); } userMapper.updateById(user); } } @Override public Borrow getById(Integer id) { return borrowMapper.getById(id); } @Override public void update(Borrow obj) { obj.setUpdatetime(LocalDate.now()); borrowMapper.updateById(obj); } @Override public void deleteById(Integer id) { borrowMapper.deleteById(id); } @Override public void deleteReturById(Integer id) { borrowMapper.deleteReturById(id); } @Override public Map getCountByTimeRange(String timeRange) { Map map = new HashMap<>(); Date today = new Date(); List dateRange; switch (timeRange) { case "week": dateRange = DateUtil.rangeToList(DateUtil.offsetDay(today, -6), today, DateField.DAY_OF_WEEK); break; case "month": dateRange = DateUtil.rangeToList(DateUtil.offsetDay(today, -29), today, DateField.DAY_OF_MONTH); break; case "month2": dateRange = DateUtil.rangeToList(DateUtil.offsetDay(today, -59), today, DateField.DAY_OF_MONTH); break; case "month3": dateRange = DateUtil.rangeToList(DateUtil.offsetDay(today, -89), today, DateField.DAY_OF_MONTH); break; default: dateRange = new ArrayList<>(); } List dateStrRange = datetimeToDateStr(dateRange); map.put("date", dateStrRange); List borrowCount = borrowMapper.getCountByTimeRange(timeRange, 1); List returnCount = borrowMapper.getCountByTimeRange(timeRange, 2); map.put("borrow", countList(borrowCount, dateStrRange)); map.put("retur", countList(returnCount, dateStrRange)); return map; } private List datetimeToDateStr(List dateTimeList) { List list = CollUtil.newArrayList(); if (CollUtil.isEmpty(dateTimeList)) { return list; } for (DateTime dateTime : dateTimeList) { String date = DateUtil.formatDate(dateTime); list.add(date); } return list; } private List countList(List countPOList, List dateRange) { List list = CollUtil.newArrayList(); if (CollUtil.isEmpty(countPOList)) { return list; } for (String date : dateRange) { Integer count = countPOList.stream().filter(countPO -> date.equals(countPO.getDate())) .map(BorrowReturCountPO::getCount).findFirst().orElse(0); list.add(count); } return list; } } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/impl/CategoryService.java ================================================ package com.example.springboot.service.impl; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.entity.Category; import com.example.springboot.mapper.CategoryMapper; import com.example.springboot.service.ICategoryService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.time.LocalDate; import java.util.List; @Service @Slf4j public class CategoryService implements ICategoryService { @Resource CategoryMapper categoryMapper; @Override public List list() { return categoryMapper.list(); } @Override public PageInfo page(BaseRequest baseRequest) { PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize()); // 自关联查询 List categories = categoryMapper.listByCondition(baseRequest); return new PageInfo<>(categories); } @Override public void save(Category obj) { categoryMapper.save(obj); } @Override public Category getById(Integer id) { return categoryMapper.getById(id); } @Override public void update(Category obj) { obj.setUpdatetime(LocalDate.now()); categoryMapper.updateById(obj); } @Override public void deleteById(Integer id) { categoryMapper.deleteById(id); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/service/impl/UserService.java ================================================ package com.example.springboot.service.impl; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; import com.example.springboot.controller.request.BaseRequest; import com.example.springboot.controller.request.UserPageRequest; import com.example.springboot.entity.User; import com.example.springboot.mapper.UserMapper; import com.example.springboot.service.IUserService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; @Service public class UserService implements IUserService { @Autowired UserMapper userMapper; @Override public List list() { return userMapper.list(); } @Override public PageInfo page(BaseRequest baseRequest) { PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize()); List users = userMapper.listByCondition(baseRequest); return new PageInfo<>(users); } @Override public void save(User user) { Date date = new Date(); // 当做卡号来处理 user.setUsername(DateUtil.format(date, "yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode())); userMapper.save(user); } @Override public User getById(Integer id) { return userMapper.getById(id); } @Override public void update(User user) { user.setUpdatetime(new Date()); userMapper.updateById(user); } @Override public void deleteById(Integer id) { userMapper.deleteById(id); } @Override public void handleAccount(User user) { Integer score = user.getScore(); if (score == null) { return; } Integer id = user.getId(); User dbUser = userMapper.getById(id); dbUser.setAccount(dbUser.getAccount() + score); userMapper.updateById(dbUser); } } ================================================ FILE: springboot/src/main/java/com/example/springboot/utils/TokenUtils.java ================================================ package com.example.springboot.utils; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.example.springboot.entity.Admin; import com.example.springboot.service.IAdminService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Date; @Component @Slf4j public class TokenUtils { private static IAdminService staticAdminService; @Resource private IAdminService adminService; @PostConstruct public void setUserService() { staticAdminService = adminService; } /** * 生成token * * @return */ public static String genToken(String adminId, String sign) { return JWT.create().withAudience(adminId) // 将 user id 保存到 token 里面,作为载荷 .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期 .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥 } public static String genToken(String adminId, String sign, int days) { return JWT.create().withAudience(adminId) // 将 user id 保存到 token 里面,作为载荷 .withExpiresAt(DateUtil.offsetDay(new Date(), days)) // 2小时后token过期 .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥 } /** * 获取当前登录的用户信息 * * @return user对象 * /admin?token=xxxx */ public static Admin getCurrentAdmin() { String token = null; try { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); token = request.getHeader("token"); if (StrUtil.isBlank(token)) { // header没有 那就从参数获取 token = request.getParameter("token"); } if (StrUtil.isBlank(token)) { log.error("获取当前登录的token失败, token: {}", token); return null; } String adminId = JWT.decode(token).getAudience().get(0); return staticAdminService.getById(Integer.valueOf(adminId)); } catch (Exception e) { log.error("获取当前登录的管理员信息失败, token={}", token, e); return null; } } } ================================================ FILE: springboot/src/main/resources/application.yml ================================================ server: port: 9090 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/library-management?serverTimezone=GMT%2b8 username: root password: 123456 mybatis: mapper-locations: classpath:mapper/*.xml configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl map-underscore-to-camel-case: true # 开启数据库字段下划线转驼峰 ================================================ FILE: springboot/src/main/resources/mapper/Admin.xml ================================================ insert into admin(username, password, phone, email) values(#{username}, #{password}, #{phone}, #{email}) update admin set username = #{username}, phone = #{phone}, email = #{email}, updatetime = #{updatetime}, status = #{status} where id = #{id} update admin set password = #{newPass} where username = #{username} and password = #{password} delete from admin where id = #{id} ================================================ FILE: springboot/src/main/resources/mapper/Book.xml ================================================ insert into book(name, description, publish_date, author, publisher, category, book_no, cover, score, nums) values(#{name}, #{description}, #{publishDate}, #{author}, #{publisher}, #{category}, #{bookNo}, #{cover}, #{score}, #{nums}) update book set name = #{name}, description = #{description}, publish_date = #{publishDate}, author = #{author}, publisher = #{publisher}, category = #{category}, book_no = #{bookNo}, cover = #{cover}, score = #{score}, nums = #{nums}, updatetime = #{updatetime} where id = #{id} update book set nums = nums + 1 where book_no = #{bookNo} delete from book where id = #{id} ================================================ FILE: springboot/src/main/resources/mapper/Borrow.xml ================================================ insert into retur(book_name, book_no, user_no, user_name, user_phone, score, days, return_date, real_date, status) values(#{bookName}, #{bookNo}, #{userNo}, #{userName}, #{userPhone}, #{score}, #{days}, #{returnDate}, #{realDate}, #{status}) insert into borrow(book_name, book_no, user_no, user_name, user_phone, score, days, return_date) values(#{bookName}, #{bookNo}, #{userNo}, #{userName}, #{userPhone}, #{score}, #{days}, #{returnDate}) update borrow set book_name = #{bookName}, book_no = #{bookNo}, user_no = #{userNo}, user_name = #{userName}, user_phone = #{userPhone}, score = #{score}, status=#{status}, days=#{days}, return_date = #{returnDate}, updatetime = #{updatetime} where id = #{id} update borrow set status = #{status} where id = #{id} delete from borrow where id = #{id} delete from retur where id = #{id} ================================================ FILE: springboot/src/main/resources/mapper/Category.xml ================================================ insert into category(name, remark, pid) values(#{name}, #{remark}, #{pid}) update category set name = #{name}, remark = #{remark}, updatetime = #{updatetime} where id = #{id} delete from category where id = #{id} ================================================ FILE: springboot/src/main/resources/mapper/User.xml ================================================ insert into user(name, username, age, sex, phone, address, account) values(#{name}, #{username}, #{age}, #{sex}, #{phone}, #{address}, #{account}) update user set name = #{name}, age = #{age}, sex = #{sex}, phone = #{phone}, address = #{address}, account = #{account}, status = #{status}, updatetime = #{updatetime} where id = #{id} delete from user where id = #{id} ================================================ FILE: springboot/src/test/java/com/example/springboot/SpringbootApplicationTests.java ================================================ package com.example.springboot; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringbootApplicationTests { @Test void contextLoads() { } } ================================================ FILE: sql/library-management.sql ================================================ /* Navicat Premium Data Transfer Source Server : localhost_3306 Source Server Type : MySQL Source Server Version : 50737 Source Host : localhost:3306 Source Schema : library-management Target Server Type : MySQL Target Server Version : 50737 File Encoding : 65001 Date: 03/11/2022 19:01:59 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for admin -- ---------------------------- DROP TABLE IF EXISTS `admin`; CREATE TABLE `admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户名', `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系方式', `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '邮箱', `createtime` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), `updatetime` datetime(0) NULL DEFAULT NULL, `password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '密码', `status` tinyint(1) NULL DEFAULT 1 COMMENT '状态', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `username_key`(`username`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of admin -- ---------------------------- INSERT INTO `admin` VALUES (1, 'admin', '13988997788', NULL, '2022-10-08 22:21:26', '2022-10-11 20:37:20', 'ead08e95e9c867a2ee833c232bf55dbc', 1); INSERT INTO `admin` VALUES (2, 'admin1', '13877889900', 'admin1@qq.com', '2022-10-10 21:28:42', '2022-10-11 20:39:41', 'a7dbef0f88b54fad3f91d010a30eff55', 1); -- ---------------------------- -- Table structure for book -- ---------------------------- DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '名称', `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '描述', `publish_date` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '出版日期', `author` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '作者', `publisher` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '出版社', `category` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '分类', `book_no` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '标准码', `cover` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '封面', `createtime` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', `updatetime` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', `score` int(10) NULL DEFAULT NULL COMMENT '积分', `nums` int(10) NULL DEFAULT 0 COMMENT '数量', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `book_no_index`(`book_no`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of book -- ---------------------------- INSERT INTO `book` VALUES (1, '西游记幼儿美绘本(全10册)', '中国四大名著之一,西游记3-8岁版,彩绘注音,有声伴读。49款夸张角色,610张精美插图, 29个西游问答,10大智力挑战,以一种超有趣的方式亲近名著经典。', '2022-10-17', '吕进1', '少年儿童出版社', '历史文化 > 唐朝文化', 'ISBN:9787558911156', 'http://img3m7.ddimg.cn/10/30/25276987-1_w_44.jpg', '2022-10-17 21:35:14', '2022-10-19 00:00:00', 10, 1); INSERT INTO `book` VALUES (6, 'Java学习指南', '2222', '2022-10-06', '222', '2', '历史文化 > 唐朝文化', 'JAVA_212113123', 'http://img3m7.ddimg.cn/10/30/25276987-1_w_44.jpg', '2022-10-17 22:30:01', '2022-10-25 00:00:00', 20, 100); INSERT INTO `book` VALUES (7, '百科全书', '3333', '2022-10-12', '33', '333', '科技 > 高新科技 > 微分子科技', 'BKQS-233131', 'http://img3m7.ddimg.cn/10/30/25276987-1_w_44.jpg', '2022-10-17 22:30:59', '2022-10-25 00:00:00', 10, 98); INSERT INTO `book` VALUES (8, '童话故事大全', '345', '2022-10-05', '55', '5', '科技 > 生物科技', 'THGS-10011122', 'http://localhost:9090/api/book/file/download/1666707290390?&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjY4MDAzMjkwfQ.FtPUrLjNRTbfzauHObyGwy0LWyrqD4VSLylW9Ef7FW8&play=1', '2022-10-17 22:32:16', '2022-10-25 00:00:00', 30, 92); INSERT INTO `book` VALUES (10, '钢铁是怎样炼成的', NULL, NULL, NULL, NULL, '历史文化 > 现代文化', 'GT-121313213', 'http://localhost:9090/api/book/file/download/1666706911257?&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjY4MDAyOTExfQ.DLB80S9v-eWBECESJiigVZooV7ks58D43KUQ2ByJQrI&play=1', '2022-10-25 22:09:08', NULL, 20, 100); -- ---------------------------- -- Table structure for borrow -- ---------------------------- DROP TABLE IF EXISTS `borrow`; CREATE TABLE `borrow` ( `id` int(11) NOT NULL AUTO_INCREMENT, `book_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '图书名称', `book_no` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '图书标准码', `user_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户会员码', `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户名称', `user_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户联系方式', `createtime` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', `updatetime` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', `score` int(10) NULL DEFAULT NULL COMMENT '借书积分', `status` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '已借出' COMMENT '借书状态', `days` int(11) NULL DEFAULT 1 COMMENT '借书天数', `return_date` datetime(0) NULL DEFAULT NULL COMMENT '归还日期', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of borrow -- ---------------------------- INSERT INTO `borrow` VALUES (2, '222', '333', '20220927-2094581083', '李芸', '138999009988', '2022-10-19 22:06:32', NULL, 10, '已借出', 2, '2022-10-21 00:00:00'); INSERT INTO `borrow` VALUES (3, '222', '22222', '20220927-2094581083', '李芸', '138999009988', '2022-10-19 22:15:28', NULL, 25, '已借出', 3, '2022-10-22 00:00:00'); INSERT INTO `borrow` VALUES (4, '222', '22222', '20220927-2094581083', '李芸', '138999009988', '2022-10-19 22:16:00', NULL, 25, '已借出', 4, '2022-10-23 00:00:00'); INSERT INTO `borrow` VALUES (5, '222', '22222', '20220927-2094581083', '李芸', '138999009988', '2022-10-19 22:16:26', NULL, 30, '已借出', 5, '2022-10-24 00:00:00'); INSERT INTO `borrow` VALUES (6, '222', '22222', '202209271239528742', '王二文案', '13988990099', '2022-10-19 22:19:18', NULL, 30, '已借出', 6, '2022-10-25 00:00:00'); INSERT INTO `borrow` VALUES (7, '222', '22222', '202209271239528742', '王二文案', '13988990099', '2022-10-19 22:19:40', NULL, 30, '已借出', 7, '2022-10-26 00:00:00'); INSERT INTO `borrow` VALUES (8, '222', '22222', '202209271239528742', '王二文案', '13988990099', '2022-10-19 22:19:47', NULL, 30, '已归还', 8, '2022-10-27 00:00:00'); INSERT INTO `borrow` VALUES (9, '222', '22222', '202209271018800687', '测试', NULL, '2022-10-19 22:30:22', NULL, 30, '已归还', 9, '2022-10-28 00:00:00'); INSERT INTO `borrow` VALUES (10, '222', '22222', '202209271018800687', '测试', NULL, '2022-10-19 22:30:47', NULL, 30, '已归还', 10, '2022-10-29 00:00:00'); INSERT INTO `borrow` VALUES (12, 'Java学习指南', 'JAVA_212113123', '202209271239528742', '苗洋洋', '13988990099', '2022-10-25 19:34:03', NULL, 20, '已归还', 3, '2022-10-28 00:00:00'); INSERT INTO `borrow` VALUES (13, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:18:25', NULL, 20, '已归还', 3, '2022-10-28 00:00:00'); INSERT INTO `borrow` VALUES (14, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:19:58', NULL, 20, '已归还', 3, '2022-10-28 00:00:00'); INSERT INTO `borrow` VALUES (15, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:23:02', NULL, 20, '已归还', 3, '2022-10-28 00:00:00'); INSERT INTO `borrow` VALUES (16, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:24:37', NULL, 20, '已归还', 3, '2022-10-28 00:00:00'); INSERT INTO `borrow` VALUES (17, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:25:49', NULL, 20, '已归还', 4, '2022-10-29 00:00:00'); INSERT INTO `borrow` VALUES (18, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:27:37', NULL, 80, '已归还', 4, '2022-10-22 00:00:00'); -- ---------------------------- -- Table structure for category -- ---------------------------- DROP TABLE IF EXISTS `category`; CREATE TABLE `category` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '名称', `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注', `pid` int(11) NULL DEFAULT NULL COMMENT '父级id', `createtime` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0), `updatetime` timestamp(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of category -- ---------------------------- INSERT INTO `category` VALUES (3, '历史文化', '历史文化', NULL, '2022-10-12 20:42:53', NULL); INSERT INTO `category` VALUES (4, '唐朝文化', '唐朝文化', 3, '2022-10-12 20:43:21', NULL); INSERT INTO `category` VALUES (5, '宋朝文化', NULL, 3, '2022-10-12 20:46:29', NULL); INSERT INTO `category` VALUES (9, '现代文化', '现代文化', 3, '2022-10-12 21:00:41', NULL); INSERT INTO `category` VALUES (10, '科技', '科技', NULL, '2022-10-12 21:50:08', NULL); INSERT INTO `category` VALUES (11, '高新科技', NULL, 10, '2022-10-12 21:50:16', NULL); INSERT INTO `category` VALUES (12, '生物科技', '生物科技', 10, '2022-10-12 21:50:22', NULL); INSERT INTO `category` VALUES (13, '微分子科技', NULL, 11, '2022-10-17 22:11:44', NULL); -- ---------------------------- -- Table structure for retur -- ---------------------------- DROP TABLE IF EXISTS `retur`; CREATE TABLE `retur` ( `id` int(11) NOT NULL AUTO_INCREMENT, `book_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '图书名称', `book_no` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '图书标准码', `user_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户会员码', `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户名称', `user_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户联系方式', `createtime` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', `updatetime` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', `score` int(10) NULL DEFAULT NULL COMMENT '借书积分', `status` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '已借出' COMMENT '借书状态', `days` int(11) NULL DEFAULT 1 COMMENT '借书天数', `return_date` datetime(0) NULL DEFAULT NULL COMMENT '归还日期', `real_date` datetime(0) NULL DEFAULT NULL COMMENT '实际归还日期', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of retur -- ---------------------------- INSERT INTO `retur` VALUES (2, 'Java学习指南', 'JAVA_212113123', '202209271239528742', '苗洋洋', '13988990099', '2022-10-25 20:18:59', NULL, 20, '已借出', 3, '2022-10-28 00:00:00', NULL); INSERT INTO `retur` VALUES (3, '222', '22222', '202209271018800687', '测试', NULL, '2022-10-25 20:21:41', NULL, 30, '已借出', 10, '2022-10-29 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (4, '222', '22222', '202209271018800687', '测试', NULL, '2022-10-25 20:21:53', NULL, 30, '已借出', 9, '2022-10-28 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (5, '222', '22222', '202209271239528742', '王二文案', '13988990099', '2022-10-25 20:21:55', NULL, 30, '已借出', 8, '2022-10-27 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (6, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:19:01', NULL, 20, '已借出', 3, '2022-10-28 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (7, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:20:04', NULL, 20, '已借出', 3, '2022-10-28 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (8, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:23:08', NULL, 20, '已借出', 3, '2022-10-28 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (9, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:24:47', NULL, 20, '已归还', 3, '2022-10-28 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (10, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:27:19', NULL, 20, '已归还', 4, '2022-10-29 00:00:00', '2022-10-25 00:00:00'); INSERT INTO `retur` VALUES (11, 'Java学习指南', 'JAVA_212113123', '20220927688792394', '杰克', '13977889988', '2022-10-25 21:28:35', NULL, 80, '已归还', 4, '2022-10-22 00:00:00', '2022-10-25 00:00:00'); -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '姓名', `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '会员码', `age` int(11) NULL DEFAULT NULL COMMENT '年龄', `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '性别', `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系方式', `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '地址', `createtime` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), `updatetime` datetime(0) NULL DEFAULT NULL, `account` int(10) NULL DEFAULT 0 COMMENT '账户余额', `status` tinyint(1) NULL DEFAULT 1 COMMENT '禁用状态 1不禁用', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `username_index`(`username`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 24 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (19, '苗洋洋', '202209271239528742', 18, '男', '13988990099', '合肥', '2022-09-27 22:10:36', '2022-10-25 19:32:13', 140, 1); INSERT INTO `user` VALUES (20, '李芸', '20220927-2094581083', 24, '女', '138999009988', '合肥', '2022-09-27 22:16:03', NULL, 20, 1); INSERT INTO `user` VALUES (21, '落布', '202209271018800687', 20, NULL, NULL, NULL, '2022-09-27 22:17:06', '2022-10-25 19:31:20', 140, 1); INSERT INTO `user` VALUES (22, '卡森', '202209271213716465', 22, '男', '13988990066', NULL, '2022-09-27 22:34:48', '2022-10-25 19:31:12', 100, 1); INSERT INTO `user` VALUES (23, '杰克', '20220927688792394', 33, '男', '13977889988', NULL, '2022-09-27 22:35:35', '2022-10-25 21:07:15', -40, 0); SET FOREIGN_KEY_CHECKS = 1; ================================================ FILE: vue/README.md ================================================ # vue ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). ================================================ FILE: vue/babel.config.js ================================================ module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ] } ================================================ FILE: vue/jsconfig.json ================================================ { "compilerOptions": { "target": "es5", "module": "esnext", "baseUrl": "./", "moduleResolution": "node", "paths": { "@/*": [ "src/*" ] }, "lib": [ "esnext", "dom", "dom.iterable", "scripthost" ] } } ================================================ FILE: vue/package.json ================================================ { "name": "vue", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build" }, "dependencies": { "axios": "^0.27.2", "core-js": "^3.8.3", "echarts": "^5.4.0", "element-ui": "^2.15.10", "js-cookie": "^3.0.1", "vue": "^2.6.14", "vue-monoplasty-slide-verify": "^1.3.1", "vue-router": "^3.5.1" }, "devDependencies": { "@vue/cli-plugin-babel": "~5.0.0", "@vue/cli-plugin-router": "~5.0.0", "@vue/cli-service": "~5.0.0", "vue-template-compiler": "^2.6.14" }, "browserslist": [ "> 1%", "last 2 versions", "not dead" ] } ================================================ FILE: vue/public/index.html ================================================ <%= htmlWebpackPlugin.options.title %>
================================================ FILE: vue/src/App.vue ================================================ ================================================ FILE: vue/src/assets/global.css ================================================ body { margin: 0; padding: 0; background-color: #eee; } * { box-sizing: border-box; } th { background-color: aliceblue !important; } ================================================ FILE: vue/src/main.js ================================================ import Vue from 'vue' import App from './App.vue' import router from './router' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; import '@/assets/global.css' import SlideVerify from 'vue-monoplasty-slide-verify'; Vue.use(SlideVerify); Vue.config.productionTip = false Vue.use(ElementUI, { size: 'small' }); // medium small mini new Vue({ router, render: h => h(App) }).$mount('#app') ================================================ FILE: vue/src/router/index.js ================================================ import Vue from 'vue' import VueRouter from 'vue-router' import Layout from '../views/Layout.vue' import Cookies from "js-cookie"; Vue.use(VueRouter) const routes = [ // ====== 登录 ===== { path: '/login', name: 'Login', component: () => import('@/views/login/Login.vue'), }, // ====== 主页 ===== { path: '/', name: 'Layout', component: Layout, redirect: '/home', children: [ // 子路由 { path: 'home', name: 'Home', component: () => import('@/views/home/HomeView.vue'), }, // ==== User ==== { path: 'userList', name: 'UserList', component: () => import('@/views/user/User.vue'), }, { path: 'addUser', name: 'AddUser', component: () => import('@/views/user/AddUser.vue'), }, { path: 'editUser', name: 'EditUser', component: () => import('@/views/user/EditUser.vue'), }, // ==== Admin ==== { path: 'adminList', name: 'AdminList', component: () => import('@/views/admin/List.vue'), }, { path: 'addAdmin', name: 'AddAdmin', component: () => import('@/views/admin/Add.vue'), }, { path: 'editAdmin', name: 'EditAdmin', component: () => import('@/views/admin/Edit.vue'), }, // ==== Category ==== { path: 'categoryList', name: 'CategoryList', component: () => import('@/views/category/List.vue') }, { path: 'addCategory', name: 'AddCategory', component: () => import('@/views/category/Add.vue') }, { path: 'editCategory', name: 'EditCategory', component: () => import('@/views/category/Edit.vue') }, // ==== Book ==== { path: 'bookList', name: 'BookList', component: () => import('@/views/book/List.vue') }, { path: 'addBook', name: 'AddBook', component: () => import('@/views/book/Add.vue') }, { path: 'editBook', name: 'EditBook', component: () => import('@/views/book/Edit.vue') }, // ==== Borrow ==== { path: 'borrowList', name: 'BorrowList', component: () => import('@/views/borrow/List.vue') }, { path: 'addBorrow', name: 'AddBorrow', component: () => import('@/views/borrow/Add.vue') }, { path: 'editBorrow', name: 'EditBorrow', component: () => import('@/views/borrow/Edit.vue') }, // ==== Return ==== { path: 'returList', name: 'returList', component: () => import('@/views/retur/List.vue') }, ] }, { path: "*", component:() => import('@/views/404') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) router.beforeEach((to, from, next) => { if (to.path === '/login') next() const admin = Cookies.get("admin") if (!admin && to.path !== '/login') return next("/login") // 强制退回到登录页面 // 访问 /home 的时候,并且cookie里面存在数据,这个时候我就直接放行 next() }) export default router ================================================ FILE: vue/src/utils/request.js ================================================ import axios from 'axios' import router from "@/router"; import Cookies from 'js-cookie' const request = axios.create({ baseURL: 'http://localhost:9090/api', timeout: 5000 }) // request 拦截器 // 可以自请求发送前对请求做一些处理 // 比如统一加token,对请求参数统一加密 request.interceptors.request.use(config => { config.headers['Content-Type'] = 'application/json;charset=utf-8'; const adminJson = Cookies.get('admin') if (adminJson) { // 设置请求头 config.headers['token'] = JSON.parse(adminJson).token } return config }, error => { return Promise.reject(error) }); // response 拦截器 // 可以在接口响应后统一处理结果 request.interceptors.response.use( response => { let res = response.data; // 兼容服务端返回的字符串数据 if (typeof res === 'string') { res = res ? JSON.parse(res) : res } if (res.code === '401') { router.push('/login') } return res; }, error => { console.log('err' + error) // for debug return Promise.reject(error) } ) export default request ================================================ FILE: vue/src/views/404.vue ================================================ ================================================ FILE: vue/src/views/Layout.vue ================================================ ================================================ FILE: vue/src/views/admin/Add.vue ================================================ ================================================ FILE: vue/src/views/admin/Edit.vue ================================================ ================================================ FILE: vue/src/views/admin/List.vue ================================================ ================================================ FILE: vue/src/views/book/Add.vue ================================================ ================================================ FILE: vue/src/views/book/Edit.vue ================================================ ================================================ FILE: vue/src/views/book/List.vue ================================================ ================================================ FILE: vue/src/views/borrow/Add.vue ================================================ ================================================ FILE: vue/src/views/borrow/Edit.vue ================================================ ================================================ FILE: vue/src/views/borrow/List.vue ================================================ ================================================ FILE: vue/src/views/category/Add.vue ================================================ ================================================ FILE: vue/src/views/category/Edit.vue ================================================ ================================================ FILE: vue/src/views/category/List.vue ================================================ ================================================ FILE: vue/src/views/home/HomeView.vue ================================================ ================================================ FILE: vue/src/views/login/Login.vue ================================================ ================================================ FILE: vue/src/views/retur/List.vue ================================================ ================================================ FILE: vue/src/views/user/AddUser.vue ================================================ ================================================ FILE: vue/src/views/user/EditUser.vue ================================================ ================================================ FILE: vue/src/views/user/User.vue ================================================ ================================================ FILE: vue/vue.config.js ================================================ const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true }) ================================================ FILE: 文档/笔记.md ================================================ # 总览 ![](图书管理.png) ## 第一节:搭建脚手架 ### 准备知识 javaSE、servlet、JDBC、Maven、Mybatis、SpringMVC、SSM(了解)、Springboot Mysql数据库简单的SQL语法 HTML、CSS、JS、vue2相关语法 ### 安装软件 关注公众号:Java学习指南,回复:软件 idea(写代码软件)、nodejs(前端开发环境)、jdk(后端开发环境)、mysql5.7\8.0(数据库)、navicat(数据库可视化)、notepad++(文本编辑器,可选)、postman(接口调试工具,可选) ### 创建vue工程 `npm config set registry https://registry.npm.taobao.org` 安装 vue/cli:https://cli.vuejs.org/zh/guide/installation.html @vue/cli@5.0.8 ### 使用elementUI 官网:https://element.eleme.cn/ 安装 ElementUI ``` npm i element-ui -S ``` ``` import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI); ``` ## 完成主页布局 ### 头部 图标网站:https://www.iconfont.cn/ ```
图书管理系统
``` ### 左侧菜单 ```
首页 关于详情
``` ### 右侧主体 ```
``` ### 写个表格试试 ```
搜索
tableData: [ { name: '王二', age: 20, address: '北京市', phone: '13899008899', sex: '男' }, { name: '王二', age: 20, address: '北京市', phone: '13899008899', sex: '男' }, { name: '王二', age: 20, address: '北京市', phone: '13899008899', sex: '女' }, ] ``` ## 搭建后台服务 ### 跨域错误 > Access to fetch at 'http://localhost:9090/user/list' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 如何解决? @CrossOrigin 百度:SpringBoot如何解决跨域问题 / Vue如何解决跨域问题 ### Mybatis官网示例 https://mybatis.net.cn/getting-started.html ```xml ``` 安装MybatisX插件 错误: > org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.springboot.mapper.UserMapper.listUsers 如何解决?配置 mapper.xml ## 后台增删改查 pageHelper ```xml com.github.pagehelper pagehelper-spring-boot-starter 1.4.5 ``` ### axios安装和使用 > npm i axios -S axios封装request.js ```javascript import axios from 'axios' const request = axios.create({ baseURL: '/api', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!! timeout: 5000 }) // request 拦截器 // 可以自请求发送前对请求做一些处理 // 比如统一加token,对请求参数统一加密 request.interceptors.request.use(config => { config.headers['Content-Type'] = 'application/json;charset=utf-8'; // config.headers['token'] = user.token; // 设置请求头 return config }, error => { return Promise.reject(error) }); // response 拦截器 // 可以在接口响应后统一处理结果 request.interceptors.response.use( response => { let res = response.data; // 兼容服务端返回的字符串数据 if (typeof res === 'string') { res = res ? JSON.parse(res) : res } return res; }, error => { console.log('err' + error) // for debug return Promise.reject(error) } ) export default request ``` 删除sql报错: > java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where id = 12' at line 如何解决?检查sql语法 常见的错误: > java.lang.IllegalArgumentException: Source must not be null 为什么会出现这个错误? 因为写代码的时候未考虑异常情况,新手常犯错误! ### 全局异常处理 ```java import com.example.springboot.common.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @Slf4j @RestControllerAdvice public class ExceptionHandle { @ExceptionHandler(value = ServiceException.class) public Result serviceExceptionError(ServiceException e) { log.error("业务异常", e); return Result.error(e.getMessage()); } @ExceptionHandler(value = Exception.class) public Result exceptionError(Exception e) { log.error("系统错误", e); return Result.error("系统错误"); } } ``` ```java public class ServiceException extends RuntimeException{ public ServiceException(String message) { super(message); } } ``` ## 登录和数据安全 js-cookie的使用 ``` npm i js-cookie -S // 导入使用 import Cookies from 'js-cookie' Cookies.set('user', obj) // 默认失效时间为该网站关闭时 Cookies.set('user', obj, { expires: 1 }) // 1天过期 Cookies.get('user') // 获取cookie数据 Cookies.remove('user') // 删除cookie数据 ``` ```sql -- 清空表数据 TRUNCATE table admin; ``` > ### Cause: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'password' at row 1 > 数据字段设置的长度不够 > ## 路由守卫 ```javascript // 404路由: { path: '*', component: () => import('@/views/404.vue'), } router.beforeEach((to, from, next) => { if (to.path === '/login') next() const admin = Cookies.get("admin") if (!admin && to.path !== '/login') return next("/login") next() }) ``` > 错误:Uncaught (in promise) Error: Redirected when going from "/login" to "/home" via a navigation guard. > > 原因:cookie数据没存,就发生了跳转,我们应该先存数据,再跳转 > > if (res.data !== null) { Cookies.set('admin', JSON.stringify(res.data)) } this.$router.push('/') > ```java // 设置自定义头配置 import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置 return new CorsFilter(source); } } ``` ## 滑块验证 开源插件地址:https://gitee.com/monoplasty/vue-monoplasty-slide-verify ```javascript npm i vue-monoplasty-slide-verify -S import SlideVerify from 'vue-monoplasty-slide-verify'; Vue.use(SlideVerify); ``` ``` 函数: onSuccess() { Cookies.set('admin', JSON.stringify(this.loginAdmin)) this.$router.push('/') this.$notify.success("登录成功") }, onFail() { }, onRefresh() { console.log('refresh') } .cover { width: fit-content; background-color: white; position: absolute; top:50%; left:50%; transform: translate(-50%, -50%); z-index: 1000; } ``` ================================================ FILE: 文档/首页Echarts.md ================================================