基于javaweb+mysql的springboot图书管理系统(java+springboot+jsp+bootstrap+maven+mysql)
运行环境
Java≥8、MySQL≥5.7
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SpringBoot图书管理系统(java+springboot+jsp+bootstrap+maven+mysql)
项目介绍
本系统分为管理员与普通用户两种角色; 管理员角色包含以下功能: 借书管理,图书信息管理,图书分类管理,用户管理,角色管理,还书管理,登录页面等功能。 用户角色包含以下功能:
借阅管理,图书检索,查看借还记录,查看图书详情,还书管理,登录页面等功能。
环境需要
1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。 2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA; 3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可 4.硬件环境:windows 7/8/10 1G内存以上;或者 Mac OS;
5.数据库:MySql 5.7版本;
6.是否Maven项目:是;
技术栈
-
后端:SpringBoot
-
前端:JSP+CSS+JavaScript+bootstrap
使用说明
- 使用Navicat或者其它工具,在mysql中创建对应名称的数据库,并导入项目的sql文件; 2. 使用IDEA/Eclipse/MyEclipse导入项目,Eclipse/MyEclipse导入时,若为maven项目请选择maven; 若为maven项目,导入成功后请执行maven clean;maven install命令,然后运行; 3. 将项目中application.properties配置文件中的数据库配置改为自己的配置; 4. 运行项目,在浏览器中输入localhost:8083/ 登录
* @description: 删除角色(先根据角色id删除角色权限关联信息, 再根据角色id删除用户角色关联信息)
*/
@DeleteMapping("/delete")
@LoginRequired
public JsonData deleteRole(@RequestParam(value = "roleId") Integer roleId) {
//TODO 根据角色id删除角色权限关联信息,再根据角色id删除用户角色关联信息
permissionService.deleteRolePermissionRsByRoleId(roleId);
roleService.deleteRoleUserRsByRoleId(roleId);
int count = roleService.deleteRole(roleId);
if (count > 0) {
return JsonData.success(count, "删除成功");
} else {
return JsonData.fail("删除失败");
}
}
/**
* @return : io.hailiang.web.book.common.DataGridDataSource<io.hailiang.web.book.model.Role>
* @description: 服务端分页查询角色列表
*/
@PostMapping("/list")
@LoginRequired
public DataGridDataSource<Role> getRoleList(@RequestParam(value = "roleName", required = false, defaultValue = "") String roleName,
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
@RequestParam(value = "rows", required = false, defaultValue = "5") Integer rows) {
PageBean pageBean = new PageBean(page, rows);
Map<String, Object> map = new HashMap<>();
map.put("roleName", "%" + roleName + "%");
map.put("start", pageBean.getStart());
map.put("size", pageBean.getPageSize());
List<Role> roleList = roleService.selectRoleList(map);
int totalRole = roleService.getTotalRole(map);
DataGridDataSource<Role> dataGridDataSource = new DataGridDataSource<>();
dataGridDataSource.setRows(roleList);
dataGridDataSource.setTotal(totalRole);
return dataGridDataSource;
}
/**
*
return JsonData.fail("新增失败");
}
}
/**
* @param bookType
* @return : io.hailiang.web.book.common.JsonData
* @description: 修改分类
*/
@PutMapping("/update")
@LoginRequired
public JsonData update(BookType bookType) {
int count = bookTypeService.updateBookType(bookType);
if (count > 0) {
return JsonData.success(count, "修改成功");
} else {
return JsonData.fail("修改失败");
}
}
}
public class LoginInterceptor implements HandlerInterceptor {
@Resource
private UserService userService;
//TODO 随机生成密码
String defaultPassword = PasswordCreateUtil.createPassWord(8);
User user = new User();
user.setUserId(userId);
user.setUserPassword(defaultPassword);
int count = userService.updateUser(user);
if (count > 0) {
mailService.sendSimpleMail(toMail, "重置密码", "您的初始密码为:" + defaultPassword);
return JsonData.success(count, "重置密码成功");
} else {
return JsonData.fail("重置密码失败");
}
}
/**
* @param userId
* @return : io.hailiang.web.book.common.JsonData
* @description: 根据用户id禁用用户
*/
@PostMapping("/disable")
@LoginRequired
public JsonData disable(@RequestParam(value = "userId") Long userId) {
User user = new User();
user.setUserId(userId);
user.setUserState(0);
int count = userService.updateUser(user);
if (count > 0) {
return JsonData.success(count, "禁用成功");
} else {
return JsonData.fail("禁用失败");
}
}
/**
* @param userId
* @return : io.hailiang.web.book.common.JsonData
* @description: 根据id启用用户
*/
@PostMapping("/enable")
@LoginRequired
public JsonData enable(@RequestParam(value = "userId") Long userId) {
User user = new User();
user.setUserId(userId);
user.setUserState(1);
int count = userService.updateUser(user);
if (count > 0) {
return JsonData.success(count, "启用成功");
} else {
return JsonData.fail("启用失败");
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//检查有没有需要用户登录的注解
User currentUser = (User) httpServletRequest.getSession().getAttribute("user");
if (method.isAnnotationPresent(LoginRequired.class)) {
LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
if (loginRequired.required()) {
if (currentUser == null) {
httpServletResponse.sendRedirect("/login.jsp");
return false;
}
}
}
//检查有没有需要用户token的注解
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 执行认证
if (token == null) {
throw new RuntimeException("token为空,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new RuntimeException("无权限访问");
}
User user = userService.findUserByUserId(Long.parseLong(userId));
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
}
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JwtUtil.SECRET)).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new RuntimeException("token失效,无权限访问");
}
return true;
}
}
return true;
/**
* @param userId
* @return : io.hailiang.web.book.common.JsonData
* @description: 查询用户信息(借书管理)
*/
@PostMapping("/userInfo")
@LoginRequired
public JsonData userInfo(Long userId) {
User user = userService.findUserByUserId(userId);
user.setUserPassword(null);
return JsonData.success(user);
}
@PostMapping("/userInfoHis")
@LoginRequired
public JsonData userInfoHis(Long userId) {
User user = userService.findUserByUserId(userId);
user.setUserPassword(null);
return JsonData.success(user);
}
}
/**
* @Auther: admin
* @Description: BookInfoController
*/
}
}
//检查有没有需要用户token的注解
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 执行认证
if (token == null) {
throw new RuntimeException("token为空,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new RuntimeException("无权限访问");
}
User user = userService.findUserByUserId(Long.parseLong(userId));
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
}
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JwtUtil.SECRET)).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new RuntimeException("token失效,无权限访问");
}
return true;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
stringBuffer.append("," + role.getRoleName());
}
u.setRoles(stringBuffer.toString().replaceFirst(",", ""));
}
int totalUser = userService.getTotalUser(map);
DataGridDataSource<User> dataGridDataSource = new DataGridDataSource<>();
dataGridDataSource.setTotal(totalUser);
dataGridDataSource.setRows(userList);
return dataGridDataSource;
}
/**
* @param userId
* @param roleIds
* @return : io.hailiang.web.book.common.JsonData
* @description: 用户角色设置(先删除当前用户拥有的角色关系, 再重新设置)
*/
@PostMapping("/saveRoleSet")
@LoginRequired
public JsonData saveRoleSet(Long userId, Integer[] roleIds) {
//先删除当前用户拥有的角色关系
roleService.deleteRoleUserRsByUserId(userId);
Map<String, Object> map = new HashMap<>();
map.put("userId", userId);
map.put("roleIds", roleIds);
int count = userService.insertUserRoles(map);
if (count > 0) {
return JsonData.success(count, "设置成功");
} else {
return JsonData.fail("设置失败");
}
}
/**
* @param oldPassword
* @param newPassword
* @param session
* @return : io.hailiang.web.book.common.JsonData
* @description: 修改密码
*/
@PostMapping("/modifyPassword")
@LoginRequired
int i = lendBookService.lendBook(lendReturnList);
//更新图书状态为借出
BookInfo bookInfo = new BookInfo();
bookInfo.setBookId(lendReturnList.getBookId());
bookInfo.setBookState(1);
bookInfoService.updateBookInfo(bookInfo);
if (i > 0) {
return JsonData.success(i, "借阅成功");
} else {
return JsonData.fail("借阅失败");
}
}
/**
*
* @param page
* @param rows
* @param session
* @return : io.hailiang.web.book.common.DataGridDataSource<io.hailiang.web.book.model.LendReturnList>
* @description: 根据用户ID查询借还记录
*/
@PostMapping("/lendreturnrecord")
@LoginRequired
public DataGridDataSource<LendReturnList> selectLendReturnRecordByUserId(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
@RequestParam(value = "rows", required = false, defaultValue = "5") Integer rows,
HttpSession session) throws ParseException {
User currentUser = (User) session.getAttribute("user");
PageBean pageBean = new PageBean(page, rows);
Map<String, Object> map = new HashMap<>();
map.put("userId", currentUser.getUserId());
map.put("start", pageBean.getStart());
map.put("size", pageBean.getPageSize());
List<LendReturnList> lendReturnLists = lendBookService.selectLendReturnRecordByUserId(map);
int totalRecord = lendBookService.getTotalRecord(map);
DataGridDataSource<LendReturnList> list = new DataGridDataSource<>();
list.setTotal(totalRecord);
list.setRows(lendReturnLists);
return list;
}
public class UserController {
@Resource
private UserService userService;
@Resource
private RoleService roleService;
@Resource
private PermissionService permissionService;
@Resource
private MailService mailService;
@Resource
private VaptchaCheckService vaptchaCheckService;
/**
* @param userName
* @param userPassword
* @return : io.hailiang.web.book.common.JsonData
* @description: 用户登录
*/
@PostMapping("/login")
public JsonData login(@RequestParam(value = "userName") String userName,
@RequestParam(value = "userPassword") String userPassword,
@RequestParam(value = "vaptchaToken") String vaptchaToken,
HttpServletRequest request,
HttpSession session) throws Exception {
if (StringUtils.isEmpty(userName)) {
return JsonData.fail("用户名不能为空!");
}
if (StringUtils.isEmpty(userPassword)) {
return JsonData.fail("密码不能为空!");
}
// if (StringUtils.isEmpty(vaptchaToken)) {
// return JsonData.fail("请进行人机验证!");
* @description: 重置用户密码并发送邮件
*/
@PostMapping("/sendMail")
@LoginRequired
public JsonData sendMail(@RequestParam(value = "toMail") String toMail,
@RequestParam(value = "userId") Long userId) {
if (StringUtils.isEmpty(toMail)) {
return JsonData.fail("用户邮箱不能为空");
}
//TODO 随机生成密码
String defaultPassword = PasswordCreateUtil.createPassWord(8);
User user = new User();
user.setUserId(userId);
user.setUserPassword(defaultPassword);
int count = userService.updateUser(user);
if (count > 0) {
mailService.sendSimpleMail(toMail, "重置密码", "您的初始密码为:" + defaultPassword);
return JsonData.success(count, "重置密码成功");
} else {
return JsonData.fail("重置密码失败");
}
}
/**
* @param userId
* @return : io.hailiang.web.book.common.JsonData
* @description: 根据用户id禁用用户
*/
@PostMapping("/disable")
@LoginRequired
public JsonData disable(@RequestParam(value = "userId") Long userId) {
User user = new User();
user.setUserId(userId);
user.setUserState(0);
int count = userService.updateUser(user);
if (count > 0) {
return JsonData.success(count, "禁用成功");
} else {
@ResponseBody
public Map<String, Object> uploadFile(MultipartFile file) throws Exception {
Map<String, Object> map = new HashMap<>();
if (!file.isEmpty()) {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String newFileName = UUID.randomUUID() + suffixName;
Date date = new Date();
int hashcode = fileName.hashCode();
int dir1 = hashcode & 0xf; //0--15
int dir2 = (hashcode & 0xf0) >> 4; //0--15
String path = uploadFilePath + new SimpleDateFormat("yyyy/MM/dd").format(date) + "/" + dir1 + "/" + dir2 + "/";
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + newFileName));
map.put("code", 0);
map.put("msg", "上传成功");
System.out.println("http://localhost:8080/uploads/" + new SimpleDateFormat("yyyy/MM/dd").format(date) + "/" + dir1 + "/" + dir2 + "/" + newFileName);
}
return map;
}
/**
* @param file
* @param CKEditorFuncNum
* @return : java.lang.String
* @description: ckeditor上传
*/
@RequestMapping(value = "/ckeditorUpload", method = RequestMethod.POST)
@ResponseBody
public String ckeditorUpload(@RequestParam("upload") MultipartFile file, String CKEditorFuncNum) throws IOException {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String newFileName = UUID.randomUUID() + suffixName;
Date date = new Date();
int hashcode = fileName.hashCode();
int dir1 = hashcode & 0xf; //0--15
int dir2 = (hashcode & 0xf0) >> 4; //0--15
String path = uploadFilePath + new SimpleDateFormat("yyyy/MM/dd").format(date) + "/" + dir1 + "/" + dir2 + "/";
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + newFileName));
//回显
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">");
return JsonData.fail("删除失败");
}
}
/**
* @param page
* @param rows
* @return : io.hailiang.web.book.common.DataGridDataSource<io.hailiang.web.book.model.BookInfo>
* @description: 图书列表
*/
@PostMapping("/list")
@LoginRequired
public DataGridDataSource<BookInfo> bookInfoList(@RequestParam(value = "bookIsbn", required = false, defaultValue = "") String bookIsbn,
@RequestParam(value = "bookName", required = false, defaultValue = "") String bookName,
@RequestParam(value = "bookAuthor", required = false, defaultValue = "") String bookAuthor,
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
@RequestParam(value = "rows", required = false, defaultValue = "10") Integer rows) {
PageBean pageBean = new PageBean(page, rows);
Map<String, Object> map = new HashMap<>();
map.put("start", pageBean.getStart());
map.put("size", pageBean.getPageSize());
map.put("bookIsbn", "%" + bookIsbn + "%");
map.put("bookName", "%" + bookName + "%");
map.put("bookAuthor", "%" + bookAuthor + "%");
List<BookInfo> bookInfoList = bookInfoService.selectBookInfoList(map);
for (BookInfo bookInfo : bookInfoList) {
List<BookType> bookTypeList = bookTypeService.selectBookTypeListByBookTypeId(bookInfo.getBookType());
for (BookType bookType : bookTypeList) {
bookInfo.setTypes(bookType.getBookTypeName());
}
}
int totalBook = bookInfoService.getTotalBook(map);
DataGridDataSource<BookInfo> bookInfoDataGridDataSource = new DataGridDataSource<>();
bookInfoDataGridDataSource.setTotal(totalBook);
bookInfoDataGridDataSource.setRows(bookInfoList);
return bookInfoDataGridDataSource;
}
/**
* @param bookId
* @return : io.hailiang.web.book.common.JsonData
* @description: 图书详情
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 获取用户的请求地址
String uri = request.getRequestURI();
// 判断当前路径是否需要进行权限验证。
// 查询所有需要验证的路径集合
List<Permission> permissions = permissionService.queryAll();
Set<String> uriSet = new HashSet<>();
for (Permission permission : permissions) {
if (permission.getPermissionUrl() != null && !"".equals(permission.getPermissionUrl())) {
uriSet.add(permission.getPermissionUrl());
}
}
if (uriSet.contains(uri)) {
// 权限验证
// 判断当前用户是否拥有对应的权限
Set<String> authUriSet = (Set<String>) request.getSession().getAttribute("authUriSet");
if (authUriSet.contains(uri)) {
return true;
} else {
response.sendRedirect("/403.jsp");
return false;
}
} else {
return true;
}
}
/**
* Intercept the execution of a handler. Called after HandlerAdapter actually
* invoked the handler, but before the DispatcherServlet renders the view.
* Can expose additional model objects to the view via the given ModelAndView.
* <p>DispatcherServlet processes a handler in an execution chain, consisting
* of any number of interceptors, with the handler itself at the end.
* With this method, each interceptor can post-process an execution,
* getting applied in inverse order of the execution chain.
* <p><strong>Note:</strong> special considerations apply for asynchronous
String path = uploadFilePath + new SimpleDateFormat("yyyy/MM/dd").format(date) + "/" + dir1 + "/" + dir2 + "/";
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + newFileName));
map.put("code", 0);
map.put("msg", "上传成功");
System.out.println("http://localhost:8080/uploads/" + new SimpleDateFormat("yyyy/MM/dd").format(date) + "/" + dir1 + "/" + dir2 + "/" + newFileName);
}
return map;
}
/**
* @param file
* @param CKEditorFuncNum
* @return : java.lang.String
* @description: ckeditor上传
*/
@RequestMapping(value = "/ckeditorUpload", method = RequestMethod.POST)
@ResponseBody
public String ckeditorUpload(@RequestParam("upload") MultipartFile file, String CKEditorFuncNum) throws IOException {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String newFileName = UUID.randomUUID() + suffixName;
Date date = new Date();
int hashcode = fileName.hashCode();
int dir1 = hashcode & 0xf; //0--15
int dir2 = (hashcode & 0xf0) >> 4; //0--15
String path = uploadFilePath + new SimpleDateFormat("yyyy/MM/dd").format(date) + "/" + dir1 + "/" + dir2 + "/";
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + newFileName));
//回显
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">");
sb.append("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + "/uploads/" + new SimpleDateFormat("yyyy/MM/dd").format(date) + "/" + dir1 + "/" + dir2 + "/" + newFileName + "','')");
sb.append("</script>");
return sb.toString();
}
}
return dataGridDataSource;
}
/**
* @param bookTypeId
* @return : io.hailiang.web.book.common.JsonData
* @description: 根据id删除分类
*/
@DeleteMapping("/delete")
@LoginRequired
public JsonData deleteBookType(@RequestParam(value = "bookTypeId") Integer bookTypeId) {
int count = bookTypeService.deleteBookType(bookTypeId);
if (count > 0) {
return JsonData.success(count, "删除成功");
} else {
return JsonData.fail("删除失败");
}
}
/**
* @param bookType
* @return : io.hailiang.web.book.common.JsonData
* @description: 新增分类
*/
@PostMapping("/save")
@LoginRequired
public JsonData saveBookType(BookType bookType) {
int count = bookTypeService.saveBookType(bookType);
if (count > 0) {
return JsonData.success(count, "新增成功");
} else {
return JsonData.fail("新增失败");
}
}
/**
* @param bookType
* @return : io.hailiang.web.book.common.JsonData
* @description: 修改分类
*/
@PutMapping("/update")
@LoginRequired
public JsonData update(BookType bookType) {
int count = bookTypeService.updateBookType(bookType);
@GetMapping("/admin/permission")
@LoginRequired
public String adminPermission() {
return "admin/permission";
}
@GetMapping("/admin/booktype")
@LoginRequired
public String adminBookType() {
return "admin/booktype";
}
@GetMapping("/admin/bookinfo")
@LoginRequired
public String adminBookInfo() {
return "admin/bookinfo";
}
@GetMapping("/admin/booklend")
@LoginRequired
public String adminBookLend() {
return "admin/booklend";
}
@GetMapping("/admin/bookreturn")
@LoginRequired
public String adminBookReturn() {
return "admin/bookreturn";
}
@GetMapping("/admin/booksearch")
@LoginRequired
public String adminBookSearch() {
return "admin/booksearch";
}
@GetMapping("/admin/lendrecord")
@LoginRequired
public String adminLendRecord() {
return "admin/lendrecord";
}
@GetMapping("/admin/bookhis")
@LoginRequired
user.setUserId(userId);
user.setUserState(0);
int count = userService.updateUser(user);
if (count > 0) {
return JsonData.success(count, "禁用成功");
} else {
return JsonData.fail("禁用失败");
}
}
/**
* @param userId
* @return : io.hailiang.web.book.common.JsonData
* @description: 根据id启用用户
*/
@PostMapping("/enable")
@LoginRequired
public JsonData enable(@RequestParam(value = "userId") Long userId) {
User user = new User();
user.setUserId(userId);
user.setUserState(1);
int count = userService.updateUser(user);
if (count > 0) {
return JsonData.success(count, "启用成功");
} else {
return JsonData.fail("启用失败");
}
}
/**
* @param userName
* @param userEmail
* @param userPhone
* @param page
* @param rows
* @return : io.hailiang.web.book.common.DataGridDataSource<io.hailiang.web.book.model.User>
@Controller
public class AdminDispatcherController {
@GetMapping("/")
public String login() {
return "redirect:login.jsp";
}
@GetMapping("/logout")
@LoginRequired
public String logout(HttpSession session) {
session.invalidate();
return "redirect:login.jsp";
}
@GetMapping("/admin/index")
@LoginRequired
public String admin() {
return "admin/index";
}
@GetMapping("/admin/user")
@LoginRequired
public String adminUser() {
return "admin/user";
}
@GetMapping("/admin/role")
@LoginRequired
public String adminRole() {
return "admin/role";
}
@GetMapping("/admin/permission")
@LoginRequired
public String adminPermission() {
return "admin/permission";
}
@GetMapping("/admin/booktype")
@LoginRequired
public String adminBookType() {
return "admin/booktype";
}
@GetMapping("/admin/bookinfo")