目录
[4.@ControllerAdvice 源码分析](#4.@ControllerAdvice 源码分析)
[4.1 initHandlerMapping](#4.1 initHandlerMapping)
[4.2 initHandlerAdapters(context)](#4.2 initHandlerAdapters(context))
[4.3 initHandlerExceptionResolvers(context)](#4.3 initHandlerExceptionResolvers(context))
[5.1 登录页面](#5.1 登录页面)
[5.2 图书列表](#5.2 图书列表)
[5.3 其他](#5.3 其他)
[5.3.1 查询图书](#5.3.1 查询图书)
[5.3.2 更新图书](#5.3.2 更新图书)
[5.3.3 删除图书](#5.3.3 删除图书)
[5.3.4 批量删除](#5.3.4 批量删除)
[5.3.5 添加图书](#5.3.5 添加图书)
书接上文:Java EE 进阶:11. SpringBoot 统一功能处理(第三弹):统一数据返回格式+统一异常处理~~
4.@ControllerAdvice 源码分析
统一数据返回和统一异常都是基于 @ControllerAdvice 注解来实现的, 通过分析
@ControllerAdvice 的源码, 可以知道他们的执行流程.
点击 @ControllerAdvice 实现源码如下:
java@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface ControllerAdvice { @AliasFor("basePackages") String[] value() default {}; @AliasFor("value") String[] basePackages() default {}; Class<?>[] basePackageClasses() default {}; Class<?>[] assignableTypes() default {}; Class<? extends Annotation>[] annotations() default {}; }从上述源码可以看出 @ControllerAdvice 派生于 @Component 组件, 这也就是为什么没有五
大注解, ControllerAdvice 就生效的原因.
下面我们看看 Spring 是怎么实现的, 还是从 DispatcherServlet 的代码开始分析.
DispatcherServlet 对象在创建时会初始化一系列的对象:(这九大组件就是 Spring 给我们进行的一些封装)
javapublic class DispatcherServlet extends FrameworkServlet { //... @Override protected void onRefresh(ApplicationContext context) { initStrategies(context); } /** * Initialize the strategy objects that this servlet uses. * <p>May be overridden in subclasses in order to initialize further * strategy objects. */ protected void initStrategies(ApplicationContext context) { initMultipartResolver(context);//文件管理的解决器 initLocaleResolver(context);//区域的处理器 initThemeResolver(context);//主题的解决方法 initHandlerMappings(context);//做映射,咱们用到的比较多的 initHandlerAdapters(context);//做适配器的处理,咱们用到的比较多的 initHandlerExceptionResolvers(context);//异常的解决器,咱们用到的比较多的 initRequestToViewNameTranslator(context);//视图相关的 initViewResolvers(context);//视图相关的 initFlashMapManager(context); } //... }对于 @ControllerAdvice 注解,我们重点关注 initHandlerMapping、 initHandlerAdapters(context) 和
initHandlerExceptionResolvers(context) 这三个方法.
4.1 initHandlerMapping
javaprivate void initHandlerMappings(ApplicationContext context) { this.handlerMappings = null;//首先它是为null的 if (this.detectAllHandlerMappings) { // Find all HandlerMappings in the ApplicationContext, including ancestor contexts. Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);//根据类型去查找HandlerMapping这样的类型,找到了就放在Map里 if (!matchingBeans.isEmpty()) { this.handlerMappings = new ArrayList<>(matchingBeans.values()); // We keep HandlerMappings in sorted order. AnnotationAwareOrderComparator.sort(this.handlerMappings);//排序 } } else { try { HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); this.handlerMappings = Collections.singletonList(hm); } catch (NoSuchBeanDefinitionException ex) { // Ignore, we'll add a default HandlerMapping later. } }4.2 initHandlerAdapters(context)
initHandlerAdapters(context) 方法会取得所有实现了 HandlerAdapter 接口的 bean 并
保存起来,其中有一个类型为 RequestMappingHandlerAdapter 的 bean,这个 bean 就是
@RequestMapping 注解能起作用的关键,这个 bean 在应用启动过程中会获取所有被
@ControllerAdvice 注解标注的 bean 对象, 并做进一步处理,关键代码如下:
javapublic class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware, InitializingBean { //... /** * 添加ControllerAdvice bean的处理 */ private void initControllerAdviceCache() { if (getApplicationContext() == null) { return; } //获取所有被 @ControllerAdvice 注解标注的bean对象 List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext()); List<Object> requestResponseBodyAdviceBeans = new ArrayList<>(); for (ControllerAdviceBean adviceBean : adviceBeans) { Class<?> beanType = adviceBean.getBeanType(); if (beanType == null) { throw new IllegalStateException("Unresolvable type for ControllerAdviceBean: " + adviceBean); } Set<Method> attrMethods = MethodIntrospector.selectMethods(beanType, MODEL_ATTRIBUTE_METHODS); if (!attrMethods.isEmpty()) { this.modelAttributeAdviceCache.put(adviceBean, attrMethods); } Set<Method> binderMethods = MethodIntrospector.selectMethods(beanType, INIT_BINDER_METHODS); if (!binderMethods.isEmpty()) { this.initBinderAdviceCache.put(adviceBean, binderMethods); } if (RequestBodyAdvice.class.isAssignableFrom(beanType) || ResponseBodyAdvice.class.isAssignableFrom(beanType)) { requestResponseBodyAdviceBeans.add(adviceBean); } } if (!requestResponseBodyAdviceBeans.isEmpty()) { this.requestResponseBodyAdvice.addAll(0, requestResponseBodyAdviceBeans); } if (logger.isDebugEnabled()) { int modelSize = this.modelAttributeAdviceCache.size(); int binderSize = this.initBinderAdviceCache.size(); int reqCount = getBodyAdviceCount(RequestBodyAdvice.class); int resCount = getBodyAdviceCount(ResponseBodyAdvice.class); if (modelSize == 0 && binderSize == 0 && reqCount == 0 && resCount == 0) { logger.debug("ControllerAdvice beans: none"); } else { logger.debug("ControllerAdvice beans: " + modelSize + " @ModelAttribute, " + binderSize + " @InitBinder, " + reqCount + " RequestBodyAdvice, " + resCount + " ResponseBodyAdvice"); } } } //... }这个方法在执行时会查找使用所有的 @ControllerAdvice 类,把 ResponseBodyAdvice 类
放在容器中,当发生某个事件时,调用相应的 Advice 方法,比如返回数据前调用统一数据封装
至于 DispatcherServlet 和 RequestMappingHandlerAdapter 是如何交互的这就是另一个复杂的话题了,此处不赘述, 源码部分难度比较高, 且枯燥, 大家以了解为主.
4.3 initHandlerExceptionResolvers(context)
接下来看 DispatcherServlet 的 initHandlerExceptionResolvers(context) 方法,
这个方法会取得所有实现了 HandlerExceptionResolver 接口的bean并保存起来,其中就有一
个类型为 ExceptionHandlerExceptionResolver 的 bean,这个 bean 在应用启动过程中会获
取所有被 @ControllerAdvice 注解标注的 bean 对象做进一步处理, 代码如下:
javapublic class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExceptionResolver implements ApplicationContextAware, InitializingBean { //... private void initExceptionHandlerAdviceCache() { if (getApplicationContext() == null) { return; } // 获取所有被 @ControllerAdvice 注解标注的bean对象 List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext()); for (ControllerAdviceBean adviceBean : adviceBeans) { Class<?> beanType = adviceBean.getBeanType(); if (beanType == null) { throw new IllegalStateException("Unresolvable type for ControllerAdviceBean: " + adviceBean); } ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(beanType); if (resolver.hasExceptionMappings()) { this.exceptionHandlerAdviceCache.put(adviceBean, resolver); } if (ResponseBodyAdvice.class.isAssignableFrom(beanType)) { this.responseBodyAdvice.add(adviceBean); } } if (logger.isDebugEnabled()) { int handlerSize = this.exceptionHandlerAdviceCache.size(); int adviceSize = this.responseBodyAdvice.size(); if (handlerSize == 0 && adviceSize == 0) { logger.debug("ControllerAdvice beans: none"); } else { logger.debug("ControllerAdvice beans: " + handlerSize + " @ExceptionHandler, " + adviceSize + " ResponseBodyAdvice"); } } } //... }当Controller抛出异常时, DispatcherServlet 通过 ExceptionHandlerExceptionResolver 来解析异常,而 ExceptionHandlerExceptionResolver 又通过 ExceptionHandlerMethodResolver
来解析异常, ExceptionHandlerMethodResolver 最终解析异常找到适用的@ExceptionHandler标注的方法是这里:
javapublic class ExceptionHandlerMethodResolver { //... private Method getMappedMethod(Class<? extends Throwable> exceptionType) { List<Class<? extends Throwable>> matches = new ArrayList<>(); //根据异常类型,查找匹配的异常处理方法 //比如NullPointerException会匹配两个异常处理方法: //handler(Exception e) 和 handler(NullPointerException e) for (Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) { if (mappedException.isAssignableFrom(exceptionType)) { matches.add(mappedException); } } //如果查找到多个匹配,就进行排序,找到最使用的方法。排序的规则依据抛出异常相对于声明异常的深度 //比如抛出的是NullPointerException(继承于RuntimeException,RuntimeException又继承于Exception) //相对于handler(NullPointerException e)声明的NullPointerException深度为0, //相对于handler(Exception e)声明的Exception 深度 2 //所以 handler(NullPointerException e)标注的方法会排在前面 if (!matches.isEmpty()) { if (matches.size() > 1) { matches.sort(new ExceptionDepthComparator(exceptionType)); } return this.mappedMethods.get(matches.get(0)); } else { return NO_MATCHING_EXCEPTION_HANDLER_METHOD; } } //... }
小结
(1)拦截器
定义拦截器,实现 HandlerInterceptor 这个接口,重写 preHandle 和 postHandle 这两个方法,一个是目标方法执行前,一个是目标方法执行后,在其中可以写具体逻辑
有多个拦截器就继续 add 添加就可以了
光写完这个还不够,还需要写 WebConfig,把这个拦截器配置到你的项目中才会生效
(2)统一结果返回
定义一个类,让它去实现 ResponseBodyAdvice 接口,然后重写 supports 和 beforeBodyWrite 这两个方法,supports 返回 true 表示执行这个方法,返回 false 表示不执行,请求过来之后先来判断 supports,再去看 beforeBodyWrite,并且在 supports 可以拿到请求的类、请求的方法,可以在里面写一些校验~~
用的注解是 @ControllerAdvice
(3)统一异常处理
用的注解依然是 @ControllerAdvice,还有一个注解是 @ExceptionHandler,@ResponseBody 和 @ControllerAdvice 可以合并成一个 @RestControllerAdvice,用哪个看自己需求就行了
5.案例代码
通过上面统一功能的添加, 我们后端的接口已经发生了变化(后端返回的数据格式统一变成了Result类型), 所以我们需要对前端代码进行修改
实际开发中, 后端接口的设计需要经过多方评审检查(review). 在接口设计时就会考虑格式化的统一化,尽可能的避免返工
当前是学习阶段, 给大家讲了这个接口设计的演变过程
5.1 登录页面
登录界面没有拦截, 只是返回结果发生了变化, 所以只需要根据返回结果修改对应代码即可
登录结果代码修改
修改前👇
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/login.css"> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div class="container-login"> <div class="container-pic"> <img src="pic/computer.png" width="350px"> </div> <div class="login-dialog"> <h3>登陆</h3> <div class="row"> <span>用户名</span> <input type="text" name="userName" id="userName" class="form-control"> </div> <div class="row"> <span>密码</span> <input type="password" name="password" id="password" class="form-control"> </div> <div class="row"> <button type="button" class="btn btn-info btn-lg" onclick="login()">登录</button> </div> </div> </div> <script src="js/jquery.min.js"></script> <script> function login() { $.ajax({ type:"post",//不写的时候默认是get url:"/user/login", data:{ name:$("#userName").val(), password:$("#password").val() }, success:function(result){ if(result){ //账号密码正确 location.href="book_list.html?currentPage=1"; }else{ alert("账号或密码错误"); } } }); // location.href = "book_list.html"; } </script> </body> </html>修改后👇
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/login.css"> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div class="container-login"> <div class="container-pic"> <img src="pic/computer.png" width="350px"> </div> <div class="login-dialog"> <h3>登陆</h3> <div class="row"> <span>用户名</span> <input type="text" name="userName" id="userName" class="form-control"> </div> <div class="row"> <span>密码</span> <input type="password" name="password" id="password" class="form-control"> </div> <div class="row"> <button type="button" class="btn btn-info btn-lg" onclick="login()">登录</button> </div> </div> </div> <script src="js/jquery.min.js"></script> <script> function login() { $.ajax({ type:"post",//不写的时候默认是get url:"/user/login", data:{ name:$("#userName").val(), password:$("#password").val() }, success:function(result){ if(result.code == "SUCCESS" && result.data==true){ //账号密码正确 location.href="book_list.html?currentPage=1"; }else{ alert("账号或密码错误"); } } }); // location.href = "book_list.html"; } </script> </body> </html>5.2 图书列表
这部分没发生什么变化,因为我们修改的时候就是针对那些返回类型由 String 改为 Result 的接口,然后把弹出来的信息改一改,就改这两处而已,这里就还是老样子👇
java<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>图书列表展示</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/list.css"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script src="js/jq-paginator.js"></script> </head> <body> <div class="bookContainer"> <h2>图书列表展示</h2> <div class="navbar-justify-between"> <div> <button class="btn btn-outline-info" type="button" onclick="location.href='book_add.html'">添加图书</button> <button class="btn btn-outline-info" type="button" onclick="batchDelete()">批量删除</button> </div> </div> <table> <thead> <tr> <td>选择</td> <td class="width100">图书ID</td> <td>书名</td> <td>作者</td> <td>数量</td> <td>定价</td> <td>出版社</td> <td>状态</td> <td class="width200">操作</td> </tr> </thead> <tbody> </tbody> </table> <div class="demo"> <ul id="pageContainer" class="pagination justify-content-center"></ul> </div> <script> //获取图书列表 getBookList(); function getBookList() { $.ajax({ type:"get", url:"/book/getListByPage"+location.search, success:function(result){ //判断未登录 if(result==null||result.code=="UNLOGIN"){ alert("用户未登录,请先登录"); location.href = "login.html"; // return;//啥也不干了,此时这一行可以删掉了,因为已经跳转了 } //其他情况判断,此处省略...... if(result==null || result.data == null){ return; } //把数据拿出来 var data = result.data; var books=data.records;//前端也要相应修改,之前的books等同于现在的result.records var finalHtml=""; for(var book of books){ finalHtml+='<tr>'; finalHtml+='<td><input type="checkbox" name="selectBook" value="'+book.id+'" id="selectBook" class="book-select"></td>'; finalHtml+='<td>'+book.id+'</td>'; finalHtml+='<td>'+book.bookName+'</td>'; finalHtml+='<td>'+book.author+'</td>'; finalHtml+='<td>'+book.count+'</td>'; finalHtml+='<td>'+book.price+'</td>'; finalHtml+='<td>'+book.publish+'</td>'; finalHtml+='<td>'+book.statusCN+'</td>'; finalHtml+='<td><div class="op">'; finalHtml+='<a href="book_update.html?bookId='+book.id+'">修改</a>'; finalHtml+='<a href="javascript:void(0)" onclick="deleteBook('+book.id+')">删除</a>'; finalHtml+='</div></td></tr>'; } $("tbody").html(finalHtml);//标签不用#也不用. //翻页信息 $("#pageContainer").jqPaginator({ totalCounts: data.total, //总记录数 pageSize: 10, //每页的个数 visiblePages: 5, //可视页数 // currentPage: '{{page}}', //当前页码,{{}}是官方文档给的,人家作者定义的 //也可以从后端去拿👇 currentPage:data.pageRequest.currentPage, first: '<li class="page-item"><a class="page-link">首页</a></li>', prev: '<li class="page-item"><a class="page-link" href="javascript:void(0);">上一页<\/a><\/li>', next: '<li class="page-item"><a class="page-link" href="javascript:void(0);">下一页<\/a><\/li>', last: '<li class="page-item"><a class="page-link" href="javascript:void(0);">最后一页<\/a><\/li>', page: '<li class="page-item"><a class="page-link" href="javascript:void(0);">{{page}}<\/a><\/li>', //页面初始化和页码点击时都会执行 onPageChange: function (page, type) { if(type=="change"){//change也是官方文档给的,表示当前分页,点击后完成跳转👇 location.href="book_list.html?currentPage="+page; } //此时这个就可以不要了 // console.log("第"+page+"页, 类型:"+type); } }); }, error: function (error){ if(error.status==401){ alert("用户未登录,请先登录"); location.href = "login.html"; } console.log(error); } }); } function deleteBook(id) { //...... } function batchDelete() { //...... } </script> </div> </body> </html>
5.3 其他
参考图书列表, 对删除图书, 批量删除图书,添加图书, 修改图书接口添加用户强制登录以及统一格式返回的逻辑处理
5.3.1 查询图书
修改前👇
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>修改图书</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/add.css"> </head> <body> <div class="container"> <div class="form-inline"> <h2 style="text-align: left; margin-left: 10px;"><svg xmlns="http://www.w3.org/2000/svg" width="40" fill="#17a2b8" class="bi bi-book-half" viewBox="0 0 16 16"> <path d="M8.5 2.687c.654-.689 1.782-.886 3.112-.752 1.234.124 2.503.523 3.388.893v9.923c-.918-.35-2.107-.692-3.287-.81-1.094-.111-2.278-.039-3.213.492V2.687zM8 1.783C7.015.936 5.587.81 4.287.94c-1.514.153-3.042.672-3.994 1.105A.5.5 0 0 0 0 2.5v11a.5.5 0 0 0 .707.455c.882-.4 2.303-.881 3.68-1.02 1.409-.142 2.59.087 3.223.877a.5.5 0 0 0 .78 0c.633-.79 1.814-1.019 3.222-.877 1.378.139 2.8.62 3.681 1.02A.5.5 0 0 0 16 13.5v-11a.5.5 0 0 0-.293-.455c-.952-.433-2.48-.952-3.994-1.105C10.413.809 8.985.936 8 1.783z" /> </svg> <span>修改图书</span> </h2> </div> <form id="updateBook"> <input type="hidden" class="form-control" id="bookId" name="id"> <div class="form-group"> <label for="bookName">图书名称:</label> <input type="text" class="form-control" id="bookName" name="bookName"> </div> <div class="form-group"> <label for="bookAuthor">图书作者</label> <input type="text" class="form-control" id="bookAuthor" name="author"/> </div> <div class="form-group"> <label for="bookStock">图书库存</label> <input type="text" class="form-control" id="bookStock" name="count"/> </div> <div class="form-group"> <label for="bookPrice">图书定价:</label> <input type="number" class="form-control" id="bookPrice" name="price"> </div> <div class="form-group"> <label for="bookPublisher">出版社</label> <input type="text" id="bookPublisher" class="form-control" name="publish"/> </div> <div class="form-group"> <label for="bookStatus">图书状态</label> <select class="custom-select" id="bookStatus" name="status"> <option value="1" selected>可借阅</option> <option value="2">不可借阅</option> </select> </div> <div class="form-group" style="text-align: right"> <button type="button" class="btn btn-info btn-lg" onclick="update()">确定</button> <button type="button" class="btn btn-secondary btn-lg" onclick="javascript:history.back()">返回</button> </div> </form> </div> <script type="text/javascript" src="js/jquery.min.js"></script> <script> getBookInfo(); function getBookInfo(){ //做的事情:调用我们的后端,获取到图书信息,并显示在页面上 $.ajax({ type: "get", url: "/book/queryBookById"+ location.search, success: function (bookInfo){ if(bookInfo !=null){ $("#bookId").val(bookInfo.id);//加上这一句 //先拿到,然后挨个赋值,注意一一对应,后面是后端的值 $("#bookName").val(bookInfo.bookName); $("#bookAuthor").val(bookInfo.author); $("#bookStock").val(bookInfo.count); $("#bookPrice").val(bookInfo.price); $("#bookPublisher").val(bookInfo.publish); $("#bookStatus").val(bookInfo.status); } } }); } function update() { //这里前端还是要处理一下,用户点击确认更新之后再更新,所以下面两行删掉 // alert("更新成功"); // location.href = "book_list.html" //重新写👇 $.ajax({ type: "post", url: "/book/updateBook", data: $("#updateBook").serialize(),//序列化,拿到form表单的值 success: function (result){ if(result == ""){ //更新成功。跳转到列表页面 location.href = "book_list.html?currentPage=1"; }else{ //弹个框,把错误信息弹出来 alert(result); } } }); } </script> </body> </html>修改后👇
htmlgetBookInfo(); function getBookInfo(){ //做的事情:调用我们的后端,获取到图书信息,并显示在页面上 $.ajax({ type: "get", url: "/book/queryBookById"+ location.search, success: function (result) { //下面不想改了,就让bookInfo接收result吧,同时做个校验 if (result.code == "SUCCESS" && result.data != null) {//校验非常简陋 var bookInfo = result.data; if (bookInfo != null) { $("#bookId").val(bookInfo.id);//加上这一句 //先拿到,然后挨个赋值,注意一一对应,后面是后端的值 $("#bookName").val(bookInfo.bookName); $("#bookAuthor").val(bookInfo.author); $("#bookStock").val(bookInfo.count); $("#bookPrice").val(bookInfo.price); $("#bookPublisher").val(bookInfo.publish); $("#bookStatus").val(bookInfo.status); } }else { console.log(result); } }, error: function(error){ if (error.status == 401) { //用户未登录 location.href = "login.html"; } } }); }5.3.2 更新图书
javascriptfunction update() { //这里前端还是要处理一下,用户点击确认更新之后再更新,所以下面两行删掉 // alert("更新成功"); // location.href = "book_list.html" //重新写👇 $.ajax({ type: "post", url: "/book/updateBook", data: $("#updateBook").serialize(),//序列化,拿到form表单的值 success: function (result){ if(result.code == "SUCCESS" && result.data == ""){ //更新成功。跳转到列表页面 location.href = "book_list.html?currentPage=1"; }else{ //弹个框,把错误信息弹出来 alert(result.errMsg); } } }); }5.3.3 删除图书
修改前👇
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>图书列表展示</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/list.css"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script src="js/jq-paginator.js"></script> </head> <body> <div class="bookContainer"> <h2>图书列表展示</h2> <div class="navbar-justify-between"> <div> <button class="btn btn-outline-info" type="button" onclick="location.href='book_add.html'">添加图书</button> <button class="btn btn-outline-info" type="button" onclick="batchDelete()">批量删除</button> </div> </div> <table> <thead> <tr> <td>选择</td> <td class="width100">图书ID</td> <td>书名</td> <td>作者</td> <td>数量</td> <td>定价</td> <td>出版社</td> <td>状态</td> <td class="width200">操作</td> </tr> </thead> <tbody> </tbody> </table> <div class="demo"> <ul id="pageContainer" class="pagination justify-content-center"></ul> </div> <script> //获取图书列表 getBookList(); function getBookList() { $.ajax({ type:"get", url:"/book/getListByPage"+location.search, success:function(result){ //判断未登录 if(result==null||result.code=="UNLOGIN"){ alert("用户未登录,请先登录"); location.href = "login.html"; // return;//啥也不干了,此时这一行可以删掉了,因为已经跳转了 } //其他情况判断,此处省略...... if(result==null || result.data == null){ return; } //把数据拿出来 var data = result.data; var books=data.records;//前端也要相应修改,之前的books等同于现在的result.records var finalHtml=""; for(var book of books){ finalHtml+='<tr>'; finalHtml+='<td><input type="checkbox" name="selectBook" value="'+book.id+'" id="selectBook" class="book-select"></td>'; finalHtml+='<td>'+book.id+'</td>'; finalHtml+='<td>'+book.bookName+'</td>'; finalHtml+='<td>'+book.author+'</td>'; finalHtml+='<td>'+book.count+'</td>'; finalHtml+='<td>'+book.price+'</td>'; finalHtml+='<td>'+book.publish+'</td>'; finalHtml+='<td>'+book.statusCN+'</td>'; finalHtml+='<td><div class="op">'; finalHtml+='<a href="book_update.html?bookId='+book.id+'">修改</a>'; finalHtml+='<a href="javascript:void(0)" onclick="deleteBook('+book.id+')">删除</a>'; finalHtml+='</div></td></tr>'; } $("tbody").html(finalHtml);//标签不用#也不用. //翻页信息 $("#pageContainer").jqPaginator({ totalCounts: data.total, //总记录数 pageSize: 10, //每页的个数 visiblePages: 5, //可视页数 // currentPage: '{{page}}', //当前页码,{{}}是官方文档给的,人家作者定义的 //也可以从后端去拿👇 currentPage:data.pageRequest.currentPage, first: '<li class="page-item"><a class="page-link">首页</a></li>', prev: '<li class="page-item"><a class="page-link" href="javascript:void(0);">上一页<\/a><\/li>', next: '<li class="page-item"><a class="page-link" href="javascript:void(0);">下一页<\/a><\/li>', last: '<li class="page-item"><a class="page-link" href="javascript:void(0);">最后一页<\/a><\/li>', page: '<li class="page-item"><a class="page-link" href="javascript:void(0);">{{page}}<\/a><\/li>', //页面初始化和页码点击时都会执行 onPageChange: function (page, type) { if(type=="change"){//change也是官方文档给的,表示当前分页,点击后完成跳转👇 location.href="book_list.html?currentPage="+page; } //此时这个就可以不要了 // console.log("第"+page+"页, 类型:"+type); } }); }, error: function (error){ if(error.status==401){ alert("用户未登录,请先登录"); location.href = "login.html"; } console.log(error); } }); } function deleteBook(id) { var isDelete = confirm("确认删除?"); if (isDelete) { // //删除图书 // alert("删除成功"); $.ajax({ type: "post", url: "/book/deleteBook?bookId="+ id, success: function (result){ //把更新的粘过来,就是封了层皮 if(result == ""){ //删除成功。跳转到列表页面 location.href = "book_list.html?currentPage=1"; }else{ //弹个框,把错误信息弹出来 alert(result); } } }); } } function batchDelete() { //弹一个框,点击确定返回true,点击取消返回false var isDelete = confirm("确认批量删除?"); if (isDelete) { //获取复选框的id var ids = []; $("input:checkbox[name='selectBook']:checked").each(function () { ids.push($(this).val()); }); console.log(ids); // alert("批量删除成功"); $.ajax({ type: "post", url: "/book/batchDelete?ids="+ids, success: function(result){ if(result){ //为true,进行页面跳转 location.href = "book_list.html?currentPage=1"; }else{ alert("批量删除失败"); } } }); } } </script> </div> </body> </html>修改后👇
javafunction deleteBook(id) { var isDelete = confirm("确认删除?"); if (isDelete) { // //删除图书 // alert("删除成功"); $.ajax({ type: "post", url: "/book/deleteBook?bookId="+ id, success: function (result){ //把更新的粘过来,就是封了层皮 if(result.code == "SUCCESS"&&result.data == ""){ //删除成功。跳转到列表页面 location.href = "book_list.html?currentPage=1"; }else{ //弹个框,把错误信息弹出来 alert(result.errMsg); } } }); } }5.3.4 批量删除
javafunction batchDelete() { //弹一个框,点击确定返回true,点击取消返回false var isDelete = confirm("确认批量删除?"); if (isDelete) { //获取复选框的id var ids = []; $("input:checkbox[name='selectBook']:checked").each(function () { ids.push($(this).val()); }); console.log(ids); // alert("批量删除成功"); $.ajax({ type: "post", url: "/book/batchDelete?ids="+ids, success: function(result){ if(result.code == "SUCCESS"&& result.data==true){ //为true,进行页面跳转 location.href = "book_list.html?currentPage=1"; }else{ alert("批量删除失败"); } } }); } }5.3.5 添加图书
修改前👇
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>添加图书</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/add.css"> </head> <body> <div class="container"> <div class="form-inline"> <h2 style="text-align: left; margin-left: 10px;"><svg xmlns="http://www.w3.org/2000/svg" width="40" fill="#17a2b8" class="bi bi-book-half" viewBox="0 0 16 16"> <path d="M8.5 2.687c.654-.689 1.782-.886 3.112-.752 1.234.124 2.503.523 3.388.893v9.923c-.918-.35-2.107-.692-3.287-.81-1.094-.111-2.278-.039-3.213.492V2.687zM8 1.783C7.015.936 5.587.81 4.287.94c-1.514.153-3.042.672-3.994 1.105A.5.5 0 0 0 0 2.5v11a.5.5 0 0 0 .707.455c.882-.4 2.303-.881 3.68-1.02 1.409-.142 2.59.087 3.223.877a.5.5 0 0 0 .78 0c.633-.79 1.814-1.019 3.222-.877 1.378.139 2.8.62 3.681 1.02A.5.5 0 0 0 16 13.5v-11a.5.5 0 0 0-.293-.455c-.952-.433-2.48-.952-3.994-1.105C10.413.809 8.985.936 8 1.783z" /> </svg> <span>添加图书</span> </h2> </div> <form id="addBook"> <div class="form-group"> <label for="bookName">图书名称:</label> <input type="text" class="form-control" placeholder="请输入图书名称" id="bookName" name="bookName"> </div> <div class="form-group"> <label for="bookAuthor">图书作者</label> <input type="text" class="form-control" placeholder="请输入图书作者" id="bookAuthor" name="author" /> </div> <div class="form-group"> <label for="bookStock">图书库存</label> <input type="text" class="form-control" placeholder="请输入图书库存" id="bookStock" name="count"/> </div> <div class="form-group"> <label for="bookPrice">图书定价:</label> <input type="number" class="form-control" placeholder="请输入价格" id="bookPrice" name="price"> </div> <div class="form-group"> <label for="bookPublisher">出版社</label> <input type="text" id="bookPublisher" class="form-control" placeholder="请输入图书出版社" name="publish" /> </div> <div class="form-group"> <label for="bookStatus">图书状态</label> <select class="custom-select" id="bookStatus" name="status"> <option value="1" selected>可借阅</option> <option value="2">不可借阅</option> </select> </div> <div class="form-group" style="text-align: right"> <button type="button" class="btn btn-info btn-lg" onclick="add()">确定</button> <button type="button" class="btn btn-secondary btn-lg" onclick="javascript:history.back()">返回</button> </div> </form> </div> <script type="text/javascript" src="js/jquery.min.js"></script> <script> function add() { //前端也应该进行参数校验,我们是后端,就省略了 //提交请求到后端 $.ajax({ type:"post", url:"/book/addBook", // serialize():序列化,拿到了所有input值 data: $("#addBook").serialize(), success: function(result){ if(result==""){ //添加图书成功,跳转 location.href="book_list.html"; }else{ //失败 alert(result); } } }); // alert("添加成功"); // location.href = "book_list.html"; } </script> </body> </html>修改后👇
javafunction add() { //前端也应该进行参数校验,我们是后端,就省略了 //提交请求到后端 $.ajax({ type:"post", url:"/book/addBook", // serialize():序列化,拿到了所有input值 data: $("#addBook").serialize(), success: function(result){ if(result.code == "SUCCESS" && result.data==""){ //添加图书成功,跳转 location.href="book_list.html"; }else{ //失败 alert(result.errMsg); } }, error: function (error){ if(error.status==401){ alert("用户未登录,请先登录"); location.href = "login.html"; } console.log(error); } }); // alert("添加成功"); // location.href = "book_list.html"; }到这里图书管理系统的代码就已经彻底完结了~~
图书管理系统完整测试
补充知识:过滤器
过滤器和拦截器的功能差不多~~
只是在作用时机上不同👇
对于请求的话都是在处理之前做一些操作,比如说像鉴权相关的,一个是服务的鉴权,一个是用户的鉴权
服务的鉴权:咱们现在项目的接口谁都能访问,那么我们就要加一些限制,比如你不能通过浏览器访问,我是一个内部系统,只能内部服务来访问,像这种服务的鉴权我们就会放在 filter(过滤器)来去做
用户的鉴权:有时候放在 filter 来做,有时候放在 拦截器 来做
filter 是 Servlet 的,intercept 是 Spring 的
具体差异的话大家在网上找一找了解一下就行了~~
总结
本章节主要介绍了SpringBoot 对一些统一功能的处理支持.
拦截器的实现主要分两部分: 1. 定义拦截器(实现HandlerInterceptor 接口) 2. 配置拦截器
统一数据返回格式通过@ControllerAdvice + ResponseBodyAdvice 来实现
统一异常处理使用@ControllerAdvice + @ExceptionHandler 来实现, 并且可以分异常来处理
学习了DispatcherServlet的一些源码

