Scene
Our team now faces the problem of multi-port data interface docking, in order to solve this problem we define the interface docking specification,
The front end (Android, Ios,web Front end) and back end are discussed in the format specification of the data, which determines the JSON data format:
{
"Code": "200",
"Data": {"": ""},
"Message": "Processing succeeded"
}
{
"Code": "300",
"Data": {"": ""},
"Message": "No This user"
}
Code stands for Request Processing status: 200 for normal processing, 300 for business exception handling, and 500 for system exception handling.
Data on behalf of the back of the background.
Message background prompt, normal or successful, will return the cause of the error.
Here's the problem.
It would be cumbersome to have everyone wrap the return value of each JSON view.
This is where AOP comes in, and we can take advantage of the idea of AOP wrapping up a layer before the request returns JSON and response to the client.
Implementing the steps to enable AOP
<!-- base-package 如果多个,用“,”分隔 --> <context:component-scan base-package="com.we,cn.isuyang"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 打开aop 注解 --> <aop:aspectj-autoproxy />
Creating facets
/** * JSON return tangent * <p> * for processing JSON return results * * @author Zhuangjunxiang ([email protected]) * @Date April 28, 2017 */@Component @aspect@order (2) public class Jsonreturnaspect {/** * Set paging default * <p> * If pagination does not have a value set , the default is to read from the system's configuration file * * @param pjp pointcut */@Around (value = "@annotation (org.springframework.web.bind.annotation.Re Sponsebody) @Order (1) public Object warp (final proceedingjoinpoint pjp) throws Throwable {Object list = PJ P.proceed (); if (Isreturnvoid (PJP)) {HttpServletResponse response = ((servletrequestattributes) requestcontextholder.getreq Uestattributes ()). GetResponse (); if (Isneedwrap (PJP)) {response.getwriter (). Write (Jsonutil.tojson (Success ("Operation succeeded")); } return list; } return data (list); }/** * If you need a package * * @param pjp Tangent * * @return true to indicate that */private Boolean isneedwrap is not required (final P RoceedingJoinpoint pjp) {method = Aspectutil.getmethod (PJP); Return!method.isannotationpresent (Void.class); }/** * returns null * * @param PJP * @return true: return type is Void,false: return type is not void */private Boolean Isretur Nvoid (Proceedingjoinpoint pjp) {method = Aspectutil.getmethod (PJP); class<?> returntype = Method.getreturntype (); return "void". Equals (Returntype.getname ()); }/** * The returned object after successful build * <p> * message is empty, do not prompt, not empty prompt * * @param message Success Message * @return JSON object */public static map<string, object> success (final String message) {map<string, object> Map = Maputil.map (); Map.put ("Code", StatusCode.SUCCESS.key ()); Map.put ("message", message); Map.put ("Data", ""); return map; }/** * After successful build the return object * <p> * message is empty, do not prompt, not empty then prompt * * @param message Success Messages * @return JSON Object */public static MAP<STRING, object> data (final Object data) {map<string, object> Map = Maputil.map (); Map.put ("Code", StatusCode.SUCCESS.key ()); Map.put ("message", message); Map.put ("Data", data); return map; } }
Analyze
@Component This annotation means that the object is instantiated with the spring container
@Aspect indicates that this is a slice class
@Around (value = "@annotation (org.springframework.web.bind.annotation.ResponseBody)")
Indicates that all methods with @responsebody annotations are tangent points in this facet, in other words, will be intercepted.
Attention:
The Proceedingjoinpoint parameter in the Warp method can use Joinpoint subclass Proceedingjoinpoint only for surround notification.
Each connection point type can invoke the proxy's method and obtain and change the return value. Otherwise it is with Joinpoint.
Scenario One: Assume that a function in the Conroller class does not require any return value
For example: I update an entity object I just need to return the updated results to OK, do not need to fill the data
The data format returned:
{
"Code": "200",
"Data": "",
"Message": "Processing succeeded"
}
Implementation ideas:
Gets the return value type of the function in the processing function of the slice processing class if void returns the data in the specified format.
The above isreturnvoid () is making such a judgment.
You only need to return the function to void:
@RequestMapping@ResponseBodypublic void add(long matchId, Model model) { slxSignupViewService.setAddInfo(matchId, model);}
Scenario Two: Assume that the return value of a function in the Conroller class does not require a package
Like what:
Some front-end plug-ins and third-party docking (payment) Return values are regulated,
As well as downloading the files, we are all redundant,
Implementation ideas:
To customize a @void annotation:
/** * 空注解 * <p> * 用于标识将controller层中的返回值原模原样的out出去 * * @author WangSen([email protected]) * @Date 2017年8月17日 */@Target({ ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Void {}
Add this annotation to the controller layer's method
/** * 支付完成 */@Void@ResponseBody@RequestMappingpublic void payFinish() throws IOException { alipayViewService.payFinish();}
On this facet processing class, determine if the function contains this annotation if it contains
Do not deal with the original model is returned.
The Isneedwrap () method in the Jsonreturnaspect class is to handle this requirement.
Resources
http://blog.csdn.net/zx13525079024/article/details/51884234
Customizing the JSON view of spring MVC