前言
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
如果你覺得我的部落格對你有幫助,可以給我點兒打賞,左側微信,右側支付寶。
有可能就是你的一點打賞會讓我的部落格寫的更好:)