Scene
Our team is now facing the problem of multi-terminal data interface docking. In order to solve this problem, we have defined the specifications for interface docking.
The front-end (Android, Ios, web front-end) and the back-end discussed the data format specifications and determined the data format of json:
{"code":"200","data":{"":""},"message":"processed successfully"}{"code":"300","data":{"":""},"message":"No this user"}The code represents the request processing status: 200 is normal processing, 300 is business exception processing, and 500 is system exception processing.
data represents the data returned by the background.
The message background prompt will return the error reason when it is normal or successful.
The problem is here
Wouldn't it be very troublesome to let everyone wrap the return value of each json view?
At this time, AOP will be launched. We can use the idea of aop to wrap it on a layer when the request returns to json before it has been responded to the client.
Implementation steps
Enable aop
<!-- base-package If multiple, separate with "," --> <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> <!-- Open aop annotation--> <aop:aspectj-autoproxy />
Create a section
/** * json returns the tangent face* <p> * Used to process json returns the result* * @author ZhuangJunxiang([email protected]) * @Date April 28, 2017*/@Component@Aspect@Order(2)public class JsonReturnAspect { /** * Set the paging default value* <p> * If the paging does not set the value, it will be read from the system's configuration file by default* * @param pjp tangent point*/ @Around(value = "@annotation(org.springframework.web.bind.annotation.ResponseBody)") @Order(1) public Object warp(final ProceedingJoinPoint pjp) throws Throwable { Object list = pjp.proceed(); if (isReturnVoid(pjp)) { HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getResponse(); if (isNeedWrap(pjp)) { response.getWriter().write(JsonUtil.toJson(success("operation succeeds"))); } return list; } return data(list); } /** * Is the package required* * @param pjp tangent point* * @return true means that there is no need */ private boolean isNeedWrap(final ProceedingJoinPoint pjp) { Method method = AspectUtil.getMethod(pjp); return !method.isAnnotationPresent(Void.class); } /** * Whether to return empty* * @param pjp * @return true: The return type is void, false: The return type is not void */ private boolean isReturnVoid(ProceedingJoinPoint pjp) { Method method = AspectUtil.getMethod(pjp); Class<?> returnType = method.getReturnType(); return "void".equals(returnType.getName()); } /** * Return object after successful construction* <p> * When the message is empty, no prompt is prompted, and if it is not empty, it is prompted* * @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; } /** * Return object after successful construction* <p> * When the message is empty, no prompt, and no empty prompt* * @param message Success message* @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 it
@Component This annotation means handing over this object to the spring container for instantiation.
@Aspect means this is a facet class
@Around(value = "@annotation(org.springframework.web.bind.annotation.ResponseBody)")
It means that all methods with @ResponseBody annotation are the middle point of this section, in other words, they will be intercepted.
Notice:
The ProceedingJoinPoint parameter in the warp method can only use the JoinPoint subclass ProceedingJoinPoint, only by surrounding notifications.
Each connection point type can call the proxy method and obtain and change the return value. Otherwise, it is to use JoinPoint.
Case 1: Assume that the function in the controller class does not need any return value
For example: When I update an entity object, I just need to return the update result and it is OK, and there is no need to fill in the data.
Returned data format:
{"code":"200","data":"","message":"processed successfully"}Implementation ideas:
Get the return value type of this function in the processing function of the aspect processing class. If it is void, it returns the data in the specified format.
The above isReturnVoid() is a judgment like this.
You just need to change the return value of the function to void:
@RequestMapping@ResponseBodypublic void add(long matchId, Model model) { slxSignupViewService.setAddInfo(matchId, model);}Case 2: Assume that the return value of the function in the controller class does not need to be wrapped
for example:
The return value of some front-end plug-ins and third-party docking (payment) is specified.
And download files, we are redundant.
Implementation ideas:
Customize annotation for @Void:
/** * Empty annotation* <p> * Used to identify out the return value in the controller layer as it is* * @author WangSen([email protected]) * @Date August 17, 2017*/@Target({ ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Void {}
Add this annotation to the controller layer method
/** * Payment completed*/@Void@ResponseBody@RequestMappingpublic void payFinish() throws IOException { alipayViewService.payFinish();}Determine whether this function contains this annotation on this section processing class.
Then it will not be processed and return as it is.
The isNeedWrap() method in the JsonReturnAspect class handles this requirement.
Summarize
The above is an analysis of the JSON view implementation ideas of custom spring mvc introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!