SpringMVC (request processing method receives json parameters)

SpringMVC's request processing method receives request parameters
1. Request processing method receives json parameters

1.1 Create project
1.2 Improve project
1.3 Import dependency

<!-- 配置开发SpringMVC所以来的jar包 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.1.5.RELEASE</version>
</dependency>
<!-- 配置ServletAPI依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
  <scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.8</version>
</dependency>

1.4 configure web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>dispatcherServle</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServle</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

1.5 Configure SpringMVC configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--配置自动扫描包-->
    <context:component-scan base-package="com.wangxing.springmvc.controller"></context:component-scan>
</beans>

1.6 Create HTML page

<!DOCTYPE html>
<html lang="en">
	<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
   </head>
<body>
    <table>
        <tr>
            <td colspan="2"><h1>用户注册</h1></td>
        </tr>
        <tr>
            <td>用户名:</td>
            <td><input id="username" type="text" name="username"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input id="password" type="password" name="password"/></td>
        </tr>
        <tr>
            <td>年龄:</td>
            <td><input id="myage" type="text" name="myage"/></td>
        </tr>
        <tr>
            <td>地址:</td>
            <td><input id="myaddress" type="text" name="myaddress"/></td>
        </tr>
        <tr>
            <td colspan="2"><input id="but1" type="button" value="提交" /></td>
        </tr>
    </table>
</body>
</html>

1.7. Create a jquery file in the webapp folder, and copy jquery-3.5.1.min.js into the jquery file.
Reload the jquery-3.5.1.min.js file in the jquery file once

1.8 Import jquery in the html file and send an ajax request

<script  src="jquery/jquery-3.5.1.min.js"></script>
<script>
    $(function () {
        $("#but1").click(function () {
            var username=$("#username").val();
            var password=$("#password").val();
            var myage=$("#myage").val();
            var myaddress=$("#myaddress").val();
            //组织成json数据[json对象]
            var params={"username":username,"password":password,"myage":myage,"myaddress":myaddress};
            //3.将上面组织好的json数据发送到控制器类的请求处理方法中接收处理
            $.ajax({
                //设置访问地址
                url:"http://localhost:8080/springmvc3/test1.do",
                //设置被发送的具体数据【json字符串】
                data:JSON.stringify(params),
                //设置请求提交方式
                type:"POST",
                //设置响应数据的类型是json
                datatype:"json",
                //设置请求的数据是json数据,绝对不可以省略
                contentType:"application/json",
                //设置请求发送成功以后的处理函数
                success:function(data){
                  alert(data);
                }
            });
        });
    });
</script>

Note: You cannot use jquery's post method to send ajax requests, because when jquery's post method sends an ajax request, the property value of contentType in the request header of the http protocol is not "application/json", so "Failed to load resource: the server" will appear. responded with a status of 415 (Unsupported Media Type)" error.
1.9 Create a java entity class corresponding to the submitted json data
Note: The member variable name of the java entity class is the same as the key value in the submitted json data.
1.10 Create Controller

package com.wangxing.springmvc.controller;
import com.wangxing.springmvc.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
    @RequestMapping(value = "/test1.do",method = RequestMethod.POST)
    public void   testRequest(@RequestBody UserBean userBean){
        System.out.println("username=="+userBean.getUsername());
        System.out.println("password=="+userBean.getPassword());
        System.out.println("myage=="+userBean.getMyage());
        System.out.println("myaddress=="+userBean.getMyaddress());
    }
}

11.测试
http://localhost:8080/springmvc3/register.html

Console output

@RequestBody
@RequestBody annotation receives parameters from the request body.
Generally used to process data in non-Content-Type: application/x-www-form-urlencoded encoding format, such as application/json, application/xml and other types of data.
"Content-Type: application/json" uses the annotation @RequestBody to transmit all the json data in the request body to the back end, which will then parse it and encapsulate it into a java object.
The request processing method returns json data to the browser page

package com.wangxing.springmvc.controller;

import com.wangxing.springmvc.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
    @RequestMapping(value = "/test1.do")
    @ResponseBody
    public UserBean   testRequest(){
        UserBean user1=new UserBean();
        user1.setUsername("zhangsan");
    	user1.setPassword("000000");
    	user1.setMyage(23);
    	user1.setMyaddress("西安");
        return user1;
    }

@RequestMapping(value = "/test2.do")
@ResponseBody
public List<UserBean> testRequest2(){
    UserBean user1=new UserBean();
    user1.setUsername("zhangsan");
    user1.setPassword("000000");
    user1.setMyage(23);
    user1.setMyaddress("西安");
    UserBean user2=new UserBean();
    user2.setUsername("lisi");
    user2.setPassword("111111");
    user2.setMyage(24);
    user2.setMyaddress("北京");
    List<UserBean>  userBeanList=new ArrayList<UserBean>();
    userBeanList.add(user1);
    userBeanList.add(user2);
    return userBeanList;
	}
}

http://localhost:8080/springmvc3/test1.do

{"username":"zhangsan","password":"000000","myage":23,"myaddress":"西安"}

http://localhost:8080/springmvc3/test2.do
[{“username”:“zhangsan”,“password”:“000000”,“myage”:23,“myaddress”:“西安”},{“username”:“lisi”,“password”:“111111”,“myage”:24,“myaddress”:“北京”}]

The function of @ResponseBody is actually to convert the java object into json format data [json object].

Conversion between Json object and json string
Json object—"json string JSON.stringify(json object)
json string—"Json object eval("("+json string+")");
For example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
    <script  src="jquery/jquery-3.5.1.min.js"></script>
    <script>
        $(function () {
            $("#but1").click(function () {
                //定义json对象
                var  jsonObj={id:1001,username:"zhangsan",age:23,address:"西安"};
                //alert(jsonObj); //[object Object]
                var jsonString=JSON.stringify(jsonObj);
                alert(jsonString); //{"id":1001,"username":"zhangsan","age":23,"address":"西安"}
            });
            $("#but2").click(function () {
                   //var jsonString="{\"id\":1001,\"username\":\"zhangsan\",\"age\":23,\"address\":\"西安\"}";
                   var jsonString="{'id':1001,'username':'zhangsan','age':23,'address':'西安'}";
                   var jsonObj=eval("("+jsonString+")");
                   alert(jsonObj);  //[object Object]
            });
        });
    </script>
</head>
<body>
    <input id="but1" type="button" value="json对象转换成Json字符串" /><br>
    <input id="but2" type="button" value="Json字符串转换成json对象" />
</body>
</html>

Guess you like

Origin blog.csdn.net/guoguo0717/article/details/110262180