Remember to study springboot Requestbodyadvice Responsebodyadvice restcontrolleradvice

Source: Internet
Author: User

Today the boss gave me a set of code, and then I took the past research, the style of the code is SSM + Shiro + nginx + springboot MVC architecture style, Springboot, is now a very fire framework, with Springcloud, Dubbo can complete the distribution, of course, today's focus is not here,

Today I looked at the structure of the code, roughly similar to the previous project architecture, but there are some differences:

Difference 1: Global exception handler. In the past, when writing projects, the global exception handler is defined in the code or XML (that is, declared in the code), defined in the

Aftercompletion
hashmap<string, string> msg =NewHashmap<string, string>(); if(Ex! =NULL) {Msg.put ("Result", "fail"); if(exinstanceofcrudexception) {Crudexception exception=(Crudexception) ex; Msg.put ("Messagecode", Exception.getcode ()); Msg.put ("MessageText", Ex.getmessage ()); } objectmapper Mapper=NewObjectmapper (); String JSON=mapper.writevalueasstring (msg); Response.setcontenttype ("Application/json;charset=utf-8"); Response.setheader ("Pragma", "No-cache"); Response.setheader ("Cache-control", "No-cache"); Response.setdateheader ("Expires", 0); PrintWriter out=Response.getwriter ();            Out.print (JSON);            Out.flush (); Out.close ();

This is the traditional definition of the global anomaly, after the Spring4.2, with a new wording, look at the following:

Like what:

Of course, this is written in Springboot, spring is defined in the XML, and there is not much to say. Down is a new project to use, nor is it a new way of writing, is the first time the individual saw this, finishing a bit,

In this way, the equivalent of the specified exception of the capture, @RestControllerAdvice meaning that the class as a notification class of beans, the notification class can implement the function of SPRINGAOP, can also implement the function of the interceptor, verify token, cross-domain problem is more common

This is the difference 1;

Down is the difference 2:

The JSON string decryption of the request, and the JSON encryption of the response. This is involved in the problem of encryption and decryption (temporarily not deep, this example is AES plus decryption, this example does not show the AES tool class, if necessary, please Baidu: Aesutil tool Class)

The process is:

In response to the first: Implement the Responsebodyadvice interface and implement its methods, in the Beforebodywrite method to respond to the JSON string encryption and modification operations, here you can learn from the Interceptor's post-method, or say

SPRINGAOP return notification, where I used a custom annotation check (if the controller layer has this annotation to encrypt the data--to protect some important handler), down the drying code:

@RestController
public class Indexcontroller {
@GetMapping (value = "/index/{id}", produces =mediatype.application_json_utf8_value) @JsonController (encode=true)
//encryption and decryption identification PublicObject Index (@PathVariable (required =false, value = "id") Integer ID, @RequestBody (required =false) (String name) {
List List=Resourceservice.selectall ();

//Mqsendmessage.sendmessage (Mqenums.topic,mqenums.login.getvalue () +id,new basuser ());

//assertutil.isnullorempty (null, "Sys_error");

return"Hello World" +id + "+"Jsonutils.tojson (list);}}

Everything look at the code: custom Annotations in code Jsoncontroller is the identity of the encryption, down is the configuration key link: Responsebodyadvice interface, of course, before configuring this interface to declare controlleradvice annotations.

 Packageorg.choviwu.example.base;Importcom.fasterxml.jackson.core.JsonProcessingException;ImportCom.fasterxml.jackson.databind.ObjectMapper;ImportOrg.choviwu.example.common.annatation.JsonController;ImportOrg.choviwu.example.common.util.AESUtil;ImportOrg.springframework.core.MethodParameter;ImportOrg.springframework.http.MediaType;Importorg.springframework.http.server.ServerHttpRequest;ImportOrg.springframework.http.server.ServerHttpResponse;ImportOrg.springframework.web.bind.annotation.RestControllerAdvice;ImportOrg.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;Importjava.io.IOException;ImportJava.lang.reflect.Type;/*** JSON plus decryption of the request*/@RestControllerAdvice (basepackages= "Org.choviwu") Public classResultresponseImplementsResponsebodyadvice<object> {    PrivateString key = "[Email protected]#~"; @Override Public Booleansupports (Methodparameter methodparameter, Class aclass) {return true; }    /*** Encrypt JSON *@paramo encrypted JSON *@return     */@Override PublicObject Beforebodywrite (Object o, Methodparameter methodparameter, mediatype mediatype, Class AClass, ServerHTTPRequest serverhttprequest, Serverhttpresponse serverhttpresponse) {//whether to encrypt JSON        if(Methodparameter.getmethod (). Isannotationpresent (Jsoncontroller.class) {Jsoncontroller Jsoncontroller= Methodparameter.getmethod (). Getannotation (Jsoncontroller.class); //If the encryption            if(Jsoncontroller.encode ()) {//TODOObjectmapper Objectmapper =NewObjectmapper (); Try{String result=Objectmapper.writerwithdefaultprettyprinter (). writevalueasstring (o); returnAesutil.getinstance (). Encrypt (Result,key);//Encrypt}Catch(jsonprocessingexception e) {e.printstacktrace (); }            }        }        returno; }}

This completes the operation of the cryptographic response parameters;

Down is the statement request decryption:

Directly on the code:

 Packageorg.choviwu.example.base;Importorg.apache.commons.io.IOUtils;ImportOrg.choviwu.example.common.annatation.MyConvert;ImportOrg.choviwu.example.common.annatation.convert.JsonConvert;ImportOrg.choviwu.example.common.util.AESUtil;ImportOrg.springframework.core.MethodParameter;Importorg.springframework.http.HttpHeaders;ImportOrg.springframework.http.HttpInputMessage;ImportOrg.springframework.http.converter.HttpMessageConverter;ImportOrg.springframework.web.bind.annotation.RestControllerAdvice;ImportOrg.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.lang.reflect.Type; @RestControllerAdvice Public classApirequestImplementsRequestbodyadvice {@Override Public BooleanSupports (Methodparameter methodparameter, type type, class<?extendsHttpmessageconverter<?>>AClass) {        return true; } @Override PublicObject Handleemptybody (Object o, Httpinputmessage httpinputmessage, Methodparameter methodparameter, type type, Class <?extendsHttpmessageconverter<?>>AClass) {        returno; } @Override PublicHttpinputmessage Beforebodyread (httpinputmessage httpinputmessage, Methodparameter MethodParameter, type type, Class <?extendsHttpmessageconverter<?>> AClass)throwsIOException {Try {            if(Methodparameter.getmethod (). Isannotationpresent (Myconvert.class) {Object obj=aclass.newinstance (); JsonConvert Convert=NewJsonConvert ();                Convert.convert (obj); return Newdhttpinputmessage (httpinputmessage); }        }Catch(Exception e) {}returnHttpinputmessage; } @Override PublicObject Afterbodyread (Object o, Httpinputmessage httpinputmessage, Methodparameter methodparameter, type type, Class< ?extendsHttpmessageconverter<?>>AClass) {        returno; }     Public Static classDhttpinputmessageImplementshttpinputmessage{Privatehttpheaders headers; PrivateInputStream body; PrivateString key = "[Email protected]#~";  PublicDhttpinputmessage (Httpinputmessage inputmessage)throwsIOException { This. headers =inputmessage.getheaders ();  This. BODY =Ioutils.toinputstream (Aesutil.getinstance (). Decrypt (Ioutils.tostring (Inputmessage.getbody ()), key)); } @Override PublicInputStream GetBody ()throwsIOException {returnbody; } @Override Publichttpheaders getheaders () {returnheaders; }    }}

NOTE: You must declare @requestbody in the method (Mapping) inside the controller you requested, otherwise the interceptor will not enter your Requestbodyadvice

@RequestBody (required = false) String name
Parameter fill name={"ABC"}
If you do not understand, please learn Springmvc springboot Foundation by yourself

At this point, learn to complete!
Remember the results of today's study.
2018/05/03



Remember to study springboot Requestbodyadvice Responsebodyadvice restcontrolleradvice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.