响应信息方式如下:
1.返回值为void,表示不需要框架帮我们处理响应信息,只能通过原生response获取输出流,回写响应信息
2.返回值为String(没有@ResponseBody注解),表示请求框架帮我们处理响应信息路径的转发或重定向(forward、redirect)
3.通常发送异步请求(map、list、set……),表示需要框架帮我们处理响应信息,将这些对象转换成JSON形式响应回去
①导包
②方法上面添加@ResponseBody注解,告知框架帮我们解析
我们还演示了发送请求如果是JSON形式该如何处理
发送端设置JSON形式
接收端(服务端的方法) 参数上面@RequestBody即可 domain对象接收
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script type="text/javascript">
window.onload=function () {
var testButtonEle=document.getElementById("testJ");
testButtonEle.onclick=function () {
var xhr=new XMLHttpRequest();
xhr.open("POST","testAJAX.do",true);
//如果想要发送的是json格式,需要告知浏览器解析规则
xhr.setRequestHeader("Content-type","application/json;charset=UTF-8");
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){
alert(xhr.responseText);
}
}
//发送请求
xhr.send('{"sid":1,"sname":"klxy"}');
}
}
</script>
</head>
<body>
<input id="testJ" type="button" value="测试JSON">
</body>
</html>
TestController
package controller;
import domain.Student;
import domain.User;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
public class TestController{
@ResponseBody
@RequestMapping("testAJAX.do")
public Map testAJAX(@RequestBody Student student){
System.out.println(student);
//经过业务层处理,通常会获得一些结果,并需要我们响应这些结果
//1.此处假设我们查询到一个对象,要将其返回
//Student result=new Student(1,"klxh","女");
//return result;
//2.map集合
Map map=new HashMap();
map.put("sid",1);
map.put("sname","klxx");
map.put("ssex","女");
return map;
//3.list集合......
//想让框架帮我们转化,框架本身没有对应的jar包,需要导包
//且需要告知框架这个返回值类型需要帮我们处理 @ResponseBody
}
}