玩转spring boot——AOP与表单验证
前言
AOP在大多数的情况下的应用场景是:日志和验证。至于AOP的理论知识我就不做赘述。而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示。
一、AOP入门
修改“pom.xml”文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.carter659</groupId> <artifactId>spring07</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <name>spring07</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
修改入口类文件“App.java”:
package com.github.carter659.spring07; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
控制器MainController:
package com.github.carter659.spring07; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MainController { @GetMapping("/") public String index() { return "index"; } @PostMapping("/save") public @ResponseBody Map<String, Object> save() { Map<String, Object> map = new HashMap<>(); map.put("msg", "ok"); return map; } }
我们拦截控制器中的返回Map的方法。
新建切面类文件“AopAspect.java”:
package com.github.carter659.spring07; import java.util.HashMap; import java.util.Map; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Component @Aspect public class AopAspect { @Around("execution (java.util.Map com.github.carter659.spring07.MainController.*( .. ) ) ") public Object invoke(ProceedingJoinPoint point) { Map<String, Object> map = null; try { Object[] args = point.getArgs(); Object val = point.proceed(args); map = (Map<String, Object>) val; } catch (Throwable e) { e.printStackTrace(); map = new HashMap<>(); map.put("msg", e.toString()); } map.put("aop", "拦截了一个请求"); return map; } }
如果能拦截到MainController中的方法,则会在Map中put一对键值。
templates模板:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>玩转spring boot——结合AOP</title> <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script> <script type="text/javascript"> /*<![CDATA[*/ var app = angular.module('app', []); app.controller('MainController', function($rootScope, $scope, $http) { //保存 $scope.save = function() { $http({ url : '/save', method : 'POST' }).success(function(r) { $scope.result = JSON.stringify(r) }); } }); /*]]>*/ </script> </head> <body ng-app="app" ng-controller="MainController"> <h1>玩转spring boot——结合AOP</h1> <h4> <a href="http://www.cnblogs.com/GoodHelper/">from 刘冬的博客</a> </h4> <input type="button" value="调用" ng-click="save()" /> <br /> <h3>调用结果:</h3> <p>{{result}}</p> <br /> <a href="http://www.cnblogs.com/GoodHelper/">点击访问原版博客</a> </body> </html>
运行效果:
点击调用按钮后:
二、表单验证
由于有了一节的AOP拦截,那么表单验证就完全可以实现了。但是,spring boot给我们提供了原生的表单验证实例。一些简单的验证,我建议实现spring boot自带的验证,因为它足够简单好用,而复杂的验证可以用AOP来实现。
参考:参考:https://spring.io/guides/gs/validating-form-input/
控制器:
package com.github.carter659.spring07; import java.util.HashMap; import java.util.Map; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; /** * 博客出处:http://www.cnblogs.com/GoodHelper/ * * @author 刘冬 * */ @Controller public class MainController { @GetMapping("/") public String index() { return "index"; } @PostMapping("/save") public @ResponseBody Map<String, Object> save() { Map<String, Object> map = new HashMap<>(); map.put("msg", "ok"); return map; } @PostMapping("/saveOrder") public @ResponseBody Map<String, Object> saveOrder(@RequestBody @Valid Order order) { Map<String, Object> map = new HashMap<>(); map.put("msg", "ok"); map.put("order", order); return map; } }
在要验证的方法的参数中增加@Valid注解。
修改Order类:
package com.github.carter659.spring07; import java.util.Date; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * 博客出处:http://www.cnblogs.com/GoodHelper/ * * @author 刘冬 * */ public class Order { public String id; @NotNull @Size(min = 10, max = 20) public String no; @NotNull public Date date; @Min(100) @NotNull public Integer quantity; /** * 省略 get set */ }
增加这javax.validation.constraints包下的验证注解。
修改index.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>玩转spring boot——结合AOP与表单验证</title> <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script> <script type="text/javascript"> /*<![CDATA[*/ var app = angular.module('app', []); app.controller('MainController', function($rootScope, $scope, $http) { $scope.data = { no : 'no.1234567890', date : '2017-01-01', quantity : 100 }; $scope.errors = { no : '', date : '', quantity : '' }; //保存 $scope.save = function() { $http({ url : '/save', method : 'POST' }).success(function(r) { $scope.result = JSON.stringify(r) }); } $scope.saveOrder = function() { $http({ url : '/saveOrder', method : 'POST', data : $scope.data }).success(function(r) { $scope.result = JSON.stringify(r) }).error(function(e) { $scope.result = JSON.stringify(e) $scope.errors.no = ''; $scope.errors.date = ''; $scope.errors.quantity = ''; for ( var i in e.errors) { var error = e.errors[i]; var field = $scope.errors[error.field]; if (field == undefined) continue; $scope.errors[error.field] = error.defaultMessage; } }) } }); /*]]>*/ </script> </head> <body ng-app="app" ng-controller="MainController"> <h1>玩转spring boot——结合AOP与表单验证</h1> <h4> <a href="http://www.cnblogs.com/GoodHelper/">from 刘冬的博客</a> </h4> <input type="button" value="调用" ng-click="save()" /> <br /> <br /> <input type="button" value="保存订单" ng-click="saveOrder()" /> <br /> 订单信息: <br /> <table cellspacing="1" style="background-color: #a0c6e5"> <tr> <td>编号:</td> <td><input ng-model="data.no" /></td> <td><font color="red" ng-show="errors.no">{{errors.no}}</font></td> </tr> <tr> <td>日期:</td> <td><input ng-model="data.date" /></td> <td><font color="red" ng-show="errors.date">{{errors.date}}</font></td> </tr> <tr> <td>数量:</td> <td><input ng-model="data.quantity" /></td> <td><font color="red" ng-show="errors.quantity">{{errors.quantity}}</font></td> </tr> </table> <br /> <h3>调用结果:</h3> <p>{{result}}</p> <br /> <a href="http://www.cnblogs.com/GoodHelper/">点击访问原版博客</a> </body> </html>
运行效果:
点击“保存订单”按钮:
如果提交的数据未通过验证,会返回400的http请求结果,并会回到AngularJs的http请求的error方法。
我们再对error方法的参数处理,就能实现客户端验证提示。
当表单填写正确后,我们提交请求:
代码下载:https://github.com/carter659/spring-boot-07.git
如果你觉得我的博客对你有帮助,可以给我点儿打赏,左侧微信,右侧支付宝。
有可能就是你的一点打赏会让我的博客写的更好:)