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; } }
测试