天天看点

springboot 参数传递(json数据)

springboot 参数传递(json数据)

*************************

相关注解

@RequestBody

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {
    boolean required() default true;
}
           

*************************

示例

*********************

前端页面

<script language="JavaScript" src="/jquery/jquery-3.4.1.min.js"></script>
<script>
    $(function () {
        $("#button").click(function () {
            const data = {
                name: $("#name").val(),
                age: $("#age").val()
            };

            $.post({
                url: "./hello4",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function () {

                }
            })
        })
    })
</script>
<body>
<form th:align="center">
    name: <input id="name" name="name"><br>
    age:  <input id="age" name="age"><br>
    <button id="button">提交</button>
</form>
</body>
           

*********************

controller 层

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello4")
    public String hello4(@RequestBody Person person){
        System.out.println(person);

        return person.toString();
    }
}
           

*************************

使用测试

单击button,控制台输出

Person(name=瓜田李下, age=20)
           

继续阅读