如何在SpringBoot后台接收前台传递的对象

  介绍

这期内容当中小编将会给大家带来有关如何在SpringBoot后台接收前台传递的对象,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

<强> ajax方式:

. ajax({美元   url:大敌;“后台的方式“,   ,异步:假的,   类型:大敌;“POST",   ,dataType :“json",   ,数据:JSON.stringify (formParamObj),   ,contentType: & # 39; application/json; charset=utf - 8 # 39;   ,成功:function (数据),{   if 才能;(data.isSuccess), {   ,,//成功处理方式   ,,},else  if (“403“,==,数据),{   ,,//失败方式处理   ,,}   ,}   });

<强> axios方式:

let  params =, {   ,key1: value1,   key2: value2   }   axios.post/get (url, params) (res=祝辞{   ,//处理结果   })

解决方案:

在方法的参数前面添加注解@RequestBody就可以解决

@PostMapper (“/xxx/xxxx")   public  List  getProgramList (@RequestBody  Program 程序){   ,System.out.println(程序);   ,return 零;   }

<>强落地测试:

可以通过邮差工具进行测试

<强>补充:关于SpringBoot自定义注解(解决后接收字符串参数空(前台传递json格式))

今天遇到个问题,接口方面的,请求参数如下图为json格式(测试工具使用谷歌的插件邮差)

如何在SpringBoot后台接收前台传递的对象

后台用字符串去接收为空

解决方案有以下几种

1。使用实体接收(一个参数,感觉没必要)

2。使用地图接收(参数不清晰,不想用)

3。自定义注解(本文采用)

<强>第一步:

如何在SpringBoot后台接收前台传递的对象

创建两个类代码如下:

package  com.annotation;   import  java.lang.annotation.Documented;   import  java.lang.annotation.ElementType;   import  java.lang.annotation.Retention;   import  java.lang.annotation.RetentionPolicy;   import  java.lang.annotation.Target;   @Target (ElementType.PARAMETER)   @Retention (RetentionPolicy.RUNTIME)   @Documented   public  @interface  RequestJson  {   String 价值();   } package  com.annotation;   import  java.io.BufferedReader;   import  javax.servlet.http.HttpServletRequest;   import  org.springframework.core.MethodParameter;   import  org.springframework.web.bind.support.WebDataBinderFactory;   import  org.springframework.web.context.request.NativeWebRequest;   import  org.springframework.web.method.support.HandlerMethodArgumentResolver;   import  org.springframework.web.method.support.ModelAndViewContainer;   import  com.alibaba.fastjson.JSONObject;   public  class  RequestJsonHandlerMethodArgumentResolver  implements  HandlerMethodArgumentResolver  {   @Override   public  boolean  supportsParameter (MethodParameter 参数),{   return  parameter.hasParameterAnnotation (RequestJson.class);   }   @Override   public  Object  resolveArgument (MethodParameter 参数,,ModelAndViewContainer  mavContainer,   NativeWebRequest  webRequest, WebDataBinderFactory  binderFactory), throws  Exception  {   RequestJson  RequestJson =, parameter.getParameterAnnotation (RequestJson.class);   HttpServletRequest  request =, webRequest.getNativeRequest (HttpServletRequest.class);   BufferedReader  reader =, request.getReader ();   StringBuilder  sb =, new  StringBuilder ();   char [], buf =, new  char [1024];   int 路;   while  ((rd =, reader.read (buf)), !=, 1), {   sb.append (buf, 0,, rd);   }   JSONObject  JSONObject =, JSONObject.parseObject (sb.toString ());   String  value =, requestJson.value ();   return  jsonObject.get(价值);   }   }

<强>第二步:启动类添加如下代码

如何在SpringBoot后台接收前台传递的对象

<强>第三步:后台请求(使用下图方式接受就可以了)

如何在SpringBoot后台接收前台传递的对象

如何在SpringBoot后台接收前台传递的对象