返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot前后端json数据交互的全过程记录
  • 716
分享到

SpringBoot前后端json数据交互的全过程记录

2024-04-02 19:04:59 716人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录一、参考文献二、勇敢尝试三、最终选择交互方式总结一、参考文献 原生ajax与Jquery Ajax springMVC接受JSON参数详解及常见错误总结 提交方式为 POST 时

一、参考文献

原生ajaxJquery Ajax

springMVC接受JSON参数详解及常见错误总结

  • 提交方式为 POST 时,
  • JQuery Ajax 以 application/x-www-fORM-urlencoded 上传 jsON对象 ,
  • 后端用 @RequestParam 或者Servlet 获取参数。
  • JQuery Ajax 以 application/json 上传 JSON字符串
  • 后端用 @RquestBody 获取参数。
  • 总结成表

Controller接收参数以及参数校验

AJAX POST请求中参数以form data和request payload形式在servlet中的获取方式

二、勇敢尝试

前端js发送ajax请求( application/x-www-form-urlencoded )

       var jsonObj = {"openid":"xxx","username":"Ed sheeran","passWord":"123"};
          
          $.ajax({
              type: 'POST',
              url: "/login",
              dataType: "json",
              data: JSON.stringify(jsonObj),
              success: function(data) {
                  console.log(data)
              },
              error: function() {
                  console.log("fucking error")
              }
          });

后端Servlet接受参数。前端报 200,后端报 返回值都是null

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(httpservletRequest request){
      System.err.println(request.getParameter("openid"));
      System.err.println(request.getParameter("username"));
      System.err.println(request.getParameter("password"));
}

后端改 @RequestParam 接受参数。前端报 404,后端报 Required String parameter ‘username’ is not present

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestParam("username") String username,
                    @RequestParam("password") String password,
                    @RequestParam("openid") String openid){
      System.err.println(username);
      System.err.println(password);
      System.err.println(openid);
  }

后端改 @RequestBody 接受参数。前端报 415,后端报 Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported

Http status 415 Unsupported Media Type

What is 415 ?

Http 415 Unsupported Media Type

The client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

Let’s look at the broswer ?

How to resolve 405 problem when using ajax post @ResponseBody return json data ?

  • if you use spring 4.x jar,please following me(Maven Repository-Spring 4.x.jar)
  • add related jar package

spring-WEBmvc.x.x.jar

jackson-databind.jar

jackson-core.jar

jackson-annotations.jar

  • In Spring Configuration file,add following code
<bean class="org.springframework.web.servlet.mvc.
annotation.AnnotationMethodHandlerAdapter">  
    <property name="messageConverters">  
        <list>  
            <ref bean="jsonHttpMessageConverter" />  
        </list>  
    </property>  
</bean>  

<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.
MappingJackson2HttpMessageConverter">  
    <property name="supportedMediaTypes">  
        <list>  
          <value>application/json;charset=UTF-8</value>  
        </list>  
    </property>  
</bean>
  • In ajax , set contentType : ‘application/json;charse=UTF-8’
    var data = {"name":"jsutin","age":18};
    $.ajax({  
        url : "/ASW/login.html",  
        type : "POST",  
        data : JSON.stringify(data),  
        dataType: 'json',  
        contentType:'application/json;charset=UTF-8',      
        success : function(result) {  
            console.log(result);  
        }  
    }); 

In server ,using @RequestBody anotation receive json data,and using @ResponseBody anotation response json to jsp page

@RequestMapping(value = "/login",method = RequestMethod.POST)
public @ResponseBody User login(@RequestBody User user){
    system.out.println(user.getName);
    system.out.println(user.getAge);
}

 

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Map<String,Object> map){
      System.err.println(map.get("username"));
      System.err.println(map.get("password"));
      System.err.println(map.get("openid"));
  }

前端加 contentType : “application/json”。前端报 200,后端 能接受到参数

    $.ajax({
              type: 'POST',
              url: "/login",
              dataType: "json",
              data: JSON.stringify(jsonObj),
              contentType : "application/json",
              success: function(data) {
                  console.log(data)
              },
              error: function() {
                  console.log("fucking error")
              }
          });
@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Map<String,Object> map){
      System.err.println(map.get("username"));
      System.err.println(map.get("password"));
      System.err.println(map.get("openid"));
}
}

有时候,我想在后端使用对象来获取参数。前端报 200,后端 也ok

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Form form){
      System.err.println(form);
}
}
public class Form {
  private String openid;
  private String username;
  private String password;

  public String getOpenid() {
      return openid;
  }

  public void setOpenid(String openid) {
      this.openid = openid;
  }

  public String getUsername() {
      return username;
  }

  public void setUsername(String username) {
      this.username = username;
  }

  public String getPassword() {
      return password;
  }

  public void setPassword(String password) {
      this.password = password;
  }

  @Override
  public String toString() {
      return "Form{" +
              "openid='" + openid + '\'' +
              ", username='" + username + '\'' +
              ", password='" + password + '\'' +
              '}';
  }
}

三、最终选择交互方式

前端 application/json,上传 josn字符串, 后端 使用对象 或者 Map

前端代码

       var jsonObj = {"openid":"xxx","username":"Ed sheeran","password":"123"};
          
          $.ajax({
              type: 'POST',
              url: "/login",
              dataType: "json",
              data: JSON.stringify(jsonObj),
              contentType : "application/json",
              success: function(data) {
                  console.log(data)
              },
              error: function() {
                  console.log("fucking error")
              }
          });

后端代码1

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Form form){
      System.err.println(form);
}
}

后端代码2

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Map<String,Object> map){
      System.err.println(map.get("username"));
      System.err.println(map.get("password"));
      System.err.println(map.get("openid"));
}
}

总结

到此这篇关于SpringBoot前后端json数据交互的文章就介绍到这了,更多相关SpringBoot前后端json数据交互内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot前后端json数据交互的全过程记录

本文链接: https://lsjlt.com/news/142349.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作