1. 程式人生 > >SpringMVC中的ResponseBody和RequestBody介紹

SpringMVC中的ResponseBody和RequestBody介紹

package name 客戶 1.8 ota pos spa pro 頁面

1ResponseBody 和 RequestBody

1簡介

@ResponseBody把後臺pojo轉換為json對象,返回到頁面

@RequestBody接受前臺json數據,把json數據自動封裝javaBean

2案例

導包

技術分享圖片

添加json轉換器

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!--配置一個json的轉換器,告訴springmvc使用jaskson來轉換json-->
<property name="messageConverters"> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </property> </bean>

寫一個jsp頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html> <head> <title>註冊</title> <script src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script> <script> function register() { //表單提交 var url = ${pageContext.request.contextPath}/stu/save.do;
var name = $(#name).val(); var sex = $(#sex).val(); var jsonObj = {name:name,sex:sex} var parameters = JSON.stringify(jsonObj); console.log(jsonObj); console.log(parameters); $.ajax({ type:post, url:url, contentType:application/json;charset=utf-8, data:parameters, success:function (respData) { console.log(respData) } }) } </script> </head> <body> <%--name = oyb & sex = male = {"name":"oyb","sex":"male"}--%> <form action="${pageContext.request.contextPath}/stu/save.do" method="post"> 用戶名:<input type="text" name="name" id="name"><br> 性別:<input type="text" name="sex" id="sex"><br> <input type="button" value="提交" onclick="register()"> </form> </form> </body> </html>

寫一個StudentController

package oyb.Controller;

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.ResponseBody;
import oyb.model.Student;


@Controller
@RequestMapping("/stu")
public class StudentController {


    @RequestMapping("/toReg")
    public  String toReg(  Student stu){
        System.out.println(stu);
        return "stu/register";
    }

    @RequestMapping("/save")
    /**
     * @RequestBody:把json數據轉成模型對象
     *@ResponseBody 返回json數據,把對象轉成json字符串返回客戶端
     */
    public  @ResponseBody
    Student save(@RequestBody Student stu){
        System.out.println(stu);

        return stu;
    }


}

測試

技術分享圖片

技術分享圖片

SpringMVC中的ResponseBody和RequestBody介紹